如果idx存在于另一个表中,则返回true

时间:2014-04-21 04:53:46

标签: mysql sql

如果另一个表中存在相同的idx,我正在尝试编写一个返回true的查询。

这是我想要做的。

两个表:

User (user_idx, name)
Group (group_idx, user_idx)

伪查询:

SELECT user_idx, name, (True(1)/False(0) value) as has_joined_group
FROM User
WHERE (Check if user_idx exists in Group table where group_idx is 3)

可以使用Mysql完成吗?如果是,怎么样?

3 个答案:

答案 0 :(得分:2)

SELECT u.user_idx, u.name, g.user_idx IS NOT NULL AS has_joined_group
FROM User AS u
LEFT JOIN Group AS g
ON g.user_idx = u.user_idx AND g.group_idx = 3

答案 1 :(得分:1)

SELECT 
    u.user_idx,
    u.name, 
    CASE WHEN g.user_idx IS NOT NULL AND g.group_idx = 3 THEN 1 ELSE 0 END AS has_joined_group
FROM 
    user u JOIN LEFT group g ON u.user_idx = g.user_idx

答案 2 :(得分:1)

SELECT u.user_idx, u.name, if(g.user_idx IS NOT NULL,'true','false') as  has_joined_group
FROM User AS u
LEFT JOIN Group AS g
ON g.user_idx = u.user_idx AND g.group_idx = 3