我对SQL有点新,并且在构造select语句时遇到了麻烦.我有两张桌子:
Table users
int id
varchar name
Table properties
int userID
int property
Run Code Online (Sandbox Code Playgroud)
我想要所有具有特定属性的用户记录.有没有办法让它们在一个SQL调用中,或者我是否需要首先从属性表中获取所有用户ID,然后单独选择每个用户?
使用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)
如果您想要选择每个用户只有一个属性行,我想这就是您想要的:
select
users.*
from
users,
properties
where
users.id = properties.userID
and properties.property = (whatnot);
Run Code Online (Sandbox Code Playgroud)
如果您有多个属性行匹配"whatnot"而您只需要一个,则根据您的数据库系统,您要么需要左连接,要么需要distinct子句.