2014-03-04 2 views
0

나는이 쿼리를 가지고 있으며, 수행해야 할 작업을 수행합니다. 테이블 2의 일치하는 테이블 1의 모든 레코드를 찾고 의사 열 값 1을 할당합니다. 그런 다음 테이블 2의 일치하는 레코드가없는 테이블 1의 모든 레코드를 검색하는 쿼리를 결합하여 의사를 할당합니다 이 방법이 효과적이지만 더 효과적 일 수 있다고 확신합니다.제안이 필요합니다. 예쁜 SQL 쿼리

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 여기에 사용 가능한입니다 :

편집 사전에 덕분에 - AND에 변화 WHEREhttp://sqlfiddle.com/#!2/57013a/1

+0

를 두 번째 쿼리에서 WHERE로 변경하고 마법처럼 – Strawberry

답변

1
  1. 당신은 제품 ID의 선택은 조인 조건의 일부가되고 싶어요.
  2. 두 번째 테이블에서 조인이 일치하는 레코드를 찾았는지 확인하려면 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; 
+0

작품. 도와 주셔서 감사합니다. – Vercingetorix

관련 문제