需要建议formore漂亮的SQL查询

时间:2014-03-04 07:46:15

标签: mysql sql

我有这个查询,它做它应该做的事情。 它查找表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

1 个答案:

答案 0 :(得分:1)

  1. 您希望产品ID选择成为加入条件的一部分 - 将WHERE更改为AND
  2. 您想要检查联接是否在第二个表中找到了匹配的记录 - 将aplac.placement_id更改为pplac.placement_id
  3. 所以下一个查询对你有用:

    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;