我有一个联合表,其中包含用户的 ID 及其类型。我需要能够获取类型 1 的用户 id 列表,以及一个新列来告诉他们是否具有类型 2。(还有一个用户表,我必须将其与 user_id 连接起来。)
user_user_types联合表:
user_id user_type
--- ---
100 1
100 2
200 1
350 1
350 2
400 3
我想要的结果表:(这是没有连接的)
user_id has_type_2
--- ---
100 1
200 0
350 1
我的查询看起来像这样,但目前只获取类型为 1 的查询,我还不确定如何添加一个新列来指示它们是否也具有 type=2。
SELECT user_type, user_id, u.*
FROM user_user_types ut
WHERE user_type=1
JOIN users u ON ut.user_id=u.id
对此有什么好的查询吗?谢谢!
最佳答案
对同一个表进行左连接,但包括类型 2 条件...
SELECT
ut.user_type,
ut.user_id,
u.*,
case when ut2.user_id is null then 0 else 1 end as HasType2
FROM
user_user_types ut
JOIN users u
ON ut.user_id = u.id
LEFT JOIN user_user_types ut2
ON ut.user_id = ut2.user_id
AND ut2.user_type = 2
WHERE
ut.user_type = 1
原始查询 WHERE 首先限定用户类型 = 1 的条件...从此,左连接到用户类型表,但使用相同的用户 ID,但还限定第二个表 (ut2) 也是用户type 2。通过左连接,如果没有符合条件的记录,则ut2的user id列将为null,表示其JOIN ON条件(包括type=2)没有匹配。
关于mysql - SQL 查询获取类型 1 的所有用户的列表,以及一个新列,告诉他们是否也有类型 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32686651/