Mysql 多表带条件选择
我有一个菜鸟问题,但对我来说却是一个麻烦的问题。我在三个表上使用 SELECT,其中中间一个是关系表(保存关系 - 用户 ID 与地点 ID),第一个是用户表,最后一个是地点表。我已经编写了这个完美的查询
$query = "SELECT users.Username,usrxplc.User,places.Name
FROM users,usrxplc,places
WHERE usrxplc.Place=places.ID AND usrxplc.User=users.ID"
,它可以吐出与所有用户关联的所有位置。很好,但我想仅限于特定用户。看似简单,但我被困住了。
I have a noob question but rather a troublesome one for me. I am using SELECT on three tables the middle one of which is realtional (Holds relations - ID of user against ID of Place), the first is a table of users, the last of places. I have written this perfectly woking query
$query = "SELECT users.Username,usrxplc.User,places.Name
FROM users,usrxplc,places
WHERE usrxplc.Place=places.ID AND usrxplc.User=users.ID"
That spits out all places associated with all users. Fine, but I would like to limit it only to a certain user. Seems simple, but I am stuck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用
WHERE
子句来过滤结果,因此只需为users.ID
添加一个子句:You use a
WHERE
clause to filter the results, so just add a clause forusers.ID
:只是觉得需要发布替代方案 - 您可以使用 INNER JOIN 将一个表连接到另一个表,而不是选择所有表
它在功能上与其他答案相同,但是当您进入更复杂的查询和表时,您会发现使用JOIN 允许更大的优化,因为您可以进一步限制每个单独 JOIN 获取的行,例如以下内容也是有效的,其中在连接到其他表之前限制用户
行在更复杂的查询中,或者如果这些表是更大,这将在一般来说,反过来会提供更优化的查询
Just felt the need to post the alternative - instead of selecting and all tables you can use INNER JOIN to join one table onto another
It's functionally the same as the other answer, however when you get onto more complex queries and tables you will find that using JOINs allows for greater optimisation as you are able to further limit the rows each individual JOIN gets, for example the following is also valid, where the User row is limited before joining onto other tables
In more complicated queries, or if these tables were to be far larger, this would in turn offer a more optimal query generally speaking