我正在尝试编写一个查询,如果另一个表中存在相同的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完成吗? 如果是,怎么办?

===============>>#1 票数: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

===============>>#2 票数: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

===============>>#3 票数: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

  ask by Raccoon translate from so

未解决问题?本站智能推荐: