我有这个查询,它做它应该做的事情。 它查找表1中表2中匹配的所有记录,并指定伪列值1。 然后它联合一个查询,该查询检索表1中表2中没有匹配项的所有记录,并分配伪列值0。 这有效,但我确信可以更有效地完成它。
SELECT aplac.*, 1 AS selected
FROM aux_placements aplac
JOIN product_placements pplac
ON pplac.placement_id = aplac.placement_id
WHERE pplac.product_id = 1
UNION
SELECT distinct aplac.*, 0 AS selected
FROM aux_placements aplac
WHERE placement_id NOT IN
(SELECT aplac.placement_id
FROM aux_placements aplac
JOIN product_placements pplac
ON pplac.placement_id = aplac.placement_id
WHERE pplac.product_id = 1)
我在想这样的事可能有用:
SELECT aplac.*,
CASE WHEN aplac.placement_id IS NULL
THEN 0
ELSE 1
END AS selected
FROM aux_placements aplac
LEFT OUTER JOIN product_placements pplac
ON pplac.placement_id = aplac.placement_id
WHERE pplac.product_id = 1;
任何建议表示赞赏。 提前致谢
编辑:sqlfiddle在这里可用:http://sqlfiddle.com/#!2/57013a/1
答案 0 :(得分:1)
WHERE
更改为AND
。aplac.placement_id
更改为pplac.placement_id
。所以下一个查询对你有用:
SELECT aplac.*,
CASE WHEN pplac.placement_id IS NULL
THEN 0
ELSE 1
END AS selected
FROM aux_placements aplac
LEFT OUTER JOIN product_placements pplac
ON pplac.placement_id = aplac.placement_id
AND pplac.product_id = 1;