根据另一个表的内容在SQL中选择记录

Ste*_*eve 4 sql

我对SQL有点新,并且在构造select语句时遇到了麻烦.我有两张桌子:

Table users
    int id
    varchar name

Table properties
    int userID
    int property
Run Code Online (Sandbox Code Playgroud)

我想要所有具有特定属性的用户记录.有没有办法让它们在一个SQL调用中,或者我是否需要首先从属性表中获取所有用户ID,然后单独选择每个用户?

Gar*_*ill 9

使用JOIN:

SELECT U.id, U.name, P.property FROM users U
INNER JOIN properties P ON P.userID = U.id
WHERE property = 3
Run Code Online (Sandbox Code Playgroud)


Ken*_*der 8

如果您想要选择每个用户只有一个属性行,我想这就是您想要的:

 select
     users.*
 from
     users,
     properties
 where
     users.id = properties.userID
     and properties.property = (whatnot);
Run Code Online (Sandbox Code Playgroud)

如果您有多个属性行匹配"whatnot"而您只需要一个,则根据您的数据库系统,您要么需要左连接,要么需要distinct子句.

  • 史蒂夫,不要学习这种过时的语法.学习使用显式连接. (3认同)