2017-01-20 12 views
-1

내가 가지고있는 다음과 같은 두 개의 테이블과 열MySQL의 쿼리 작동하지 않습니다 존재합니다 제대로

표 1 :는 TransactionId

표 2는 TransactionId 및 상태

나는 테이블에서 결과를 얻을 필요 1 동일한 transactionid가 table2에없는 경우

table2의 동일한 transactionid가 있지만 상태가 2와 다르면 table1 행을 반환하지 않아야합니다.

은 표 2와 동일한는 TransactionId이 존재

경우와 상태가 (2) 다음은 표 1 행을 반환해야하지만, 난 내가 현재 가지고

내 웹 사이트 내부 오류를 표시 할 수 있습니다 이것을 알아야합니다

select * from table1 where not exists (select null from table2 
      WHERE table1.transactionid = table2.transactionid AND status <> 2) 

내가 그는 TransactionId이와 표 2에 오류가있는 경우

select *, (select count(*) from table2 where table1.transactionid = table2.transactionid AND status = 2) as orderswitherrors from table1 where not exists (select null from table2 
      WHERE table1.transactionid = table2.transactionid AND status <> 2) 

그래서 PHP에서 내가 확인하실 수 있습니다 (이 제대로 작동하지 않습니다) 이런 일을해야하는 경우 ($ 로우 -> orderswitherrors> 0) .. .

고맙습니다.

답변

1

나는 당신이 너무 많은 것을 존재를 사용하여 시도하고 있다고 생각합니다.

이 쿼리에서는 조인을 사용하여 Table1과 Table2를 모두 결과 집합으로 가져옵니다. 왼쪽 조인을 사용하므로 Table1의 행은 Table2에 없더라도 반환됩니다. 일치하는 행이 없으면 결과 집합에 모든 Table2 열에 대해 NULL이 포함됩니다.

두 테이블이 모두 포함 된 결과 집합을 만들었 으면 해당 행을 필터링하여 우리는 행을 a) Table2의 행이 없거나 (b) 행과 status = 2.

SELECT table1.*, 
      table2.status 
FROM  table1 
LEFT JOIN table2 ON table1.transactionid = table2.transactionid 
WHERE  table2.transactionid IS NULL --Doesn't exist in table2 
OR  table2.status = 2    --Exists in table2 with status 2 
+0

난 당신이 당신의 대답 주위에 좀 더 컨텍스트를 추가하시기 바랍니다 요청할 수 있습니다. 코드 전용 답변은 이해하기 어렵습니다. 그것은 당신이 당신의 포스트에있는 정보를 더 추가 할 수있는 경우에 둘 다 구경꾼 및 미래 독자를 도울 것이다. – RBT

+0

http://imgur.com/a/dojSZ 그러나 도움을 주셔서 감사합니다, 나는 어떤 결과가 table2의 행 중 하나에있는 경우 1을 반환하지 않아야합니다. 감사 – lorigio

2

당신은 상태와 트랜잭션 ID를 얻을 case 문 함께 '참여 왼쪽'을 사용할 수 있으며, 상태 등을 기준으로 표시/숨기기 오류 :

SELECT t1.transactionid, 
CASE WHEN t2.status IS NULL THEN 'NOT_EXISTS' 
WHEN t2.status = 2 THEN 'ERROR' 
END AS state 
FROM table1 t1 LEFT JOIN table2 t2 ON t1.transactionid = t2.transactionid 
WHERE t2.status IS NULL OR t2.status = 2 
ORDER BY t1.transactionid; 

여기 SQL Fiddle입니다.

0

당신은 조합 NOT EXISTSEXISTS를 사용할 수 있습니다

select t1.* 
from table1 t1 
where not exists (select 1 
        from table2 t2 
        where t1.transactionid = t2.transactionid 
       ) or 
     exists (select 1 
       from table2 t2 
       where t1.transactionid = t2.transactionid and 
        status = 2 
      );