我有一张包含一些数据的表
t1
------------------
id (int)
item_id (int)
item_description (text)
showHide (enum 0,1)
通常我会显示showHide标志设置为'0'的任何结果。如果用户在另一个表t2中有相应的item_id,我需要修改查询以显示showHide标志设置为'1'的结果。
t2
------------------
id (int)
item_id (int)
usr_id (int)
坚持到这里,不知道如何做到这一点:
SELECT item_description FROM t1
// get results with showHide = 0
// AND
// showHide = 1 if t1.item_id found in t2 WHERE usr_id = 123
答案 0 :(得分:1)
只需将2个查询与UNION
SELECT t1.item_description
FROM t1
WHERE showHide = 0
UNION
SELECT t1.item_description
FROM t1
INNER JOIN t2 ON t1.item_id = t2.item_id
WHERE showHide = 1
更棘手的方式,因此性能较差:
SELECT t1.item_description
FROM t1
LEFT JOIN t2 ON t1.item_id = t2.item_id
WHERE showHide = 0
OR (showHide = 1 AND t2.item_id IS NOT NULL)
答案 1 :(得分:1)
SELECT
t1.item_description
FROM
t1
LEFT JOIN (
SELECT item_id FROM t2 WHERE usr_id = 123
) AS t2
USING (item_id)
WHERE
t1.showHide = 0
OR
(t1.showHide = 1 AND t2.item_id IS NOT NULL)