如何检查特定列是否为null然后忽略查询的某些部分
我想得到的结果包括这两行,但如果user_id
为null则无法查询
SELECT
mc.* FROM media_credit mc
LEFT JOIN credit c ON c.id = mc.credit_id
LEFT JOIN "user" u ON u.id = mc.user_id
LEFT JOIN "user" _u ON u.id = c.create_by_user_id
WHERE mc.media_id = $1
c.status = $2
AND u.status = $2 // how to make if mc.user_id is null then dont use this
AND _u.status = $2
表
media_credit
id | media_id | credit_id | username | user_id
1 | 1 | 1 | xx | null
2 | 1 | 1 | null | 1
user
id | status
1 | 0
credit
id | status | create_by_user_id
1 | 0 | 32
答案 0 :(得分:2)
您应该将WHERE
子句中的其他条件添加到ON
子句中:
SELECT mc.*
FROM media_credit mc
LEFT JOIN credit c
ON c.id = mc.credit_id
AND c.status = $2
LEFT JOIN "user" u
ON u.id = mc.user_id
AND u.status = $2
LEFT JOIN "user" _u
ON u.id = c.create_by_user_id
AND _u.status = $2
WHERE
mc.media_id = $1
当您过滤WHERE
子句中的右表时,您的LEFT JOIN
将转换为INNER JOIN
,从而删除不匹配的行。
答案 1 :(得分:1)
您可以在where子句中使用CASE语句...如果mc.user_id为NULL,则$ 2 = $ 2有效删除AND子句
SELECT
mc.* FROM media_credit mc
LEFT JOIN credit c ON c.id = mc.credit_id
LEFT JOIN "user" u ON u.id = mc.user_id
LEFT JOIN "user" _u ON u.id = c.create_by_user_id
WHERE mc.media_id = $1
c.status = $2
AND _u.status = $2
AND CASE WHEN mc.user_id is NULL THEN $2
ELSE u.status END = $2