2016-06-01 47 views
1

我有3個MySQL表來檢索它們的數據。合併3個不同的MySQL表的值,連接表1和表2,並檢查在這個連接中是否存在表3值

table1中包含行:

id | name  | total_amount | product_id | date 
--------------------------------------------- 
1 | some name | some amount | some pid | some date 
2 | some name1 | some amount1 | some pid1 | some date1 
3 | some name2 | some amount2 | some pid2 | some date2 
4 | some name3 | some amount3 | some pid3 | some date3 

和表2:

product_id | product_name 
------------------- 
some pid | some product name 
some pid1 | some product name1 
some pid2 | some product name2 
some pid3 | some product name3 

和表3:

id | total_amount | product_id 
------------------------------- 
1 | some amount | some pid 
2 | some amount2 | some pid2 

我使用的內表1和表2與他們的product_id之間加入列表值如下:

name  | total_amount | product_id | product_name  | date 
-------------------------------------------------- 
some name | some amount | some pid | some product name | some date 
some name1 | some amount1 | some pid1 | some product name1 | some date1 
some name2 | some amount2 | some pid2 | some product name2 | some date2 
some name3 | some amount3 | some pid3 | some product name3 | some date3 

但是,如果table3的total_amount和product_id與table1的total_amount和product_id具有相同的值,我不想在連接表列表中顯示行。

所以我想我的輸出如:

name  | total_amount | product_id | product_name  | date 
-------------------------------------------------- 
some name1 | some amount1 | some pid1 | some product name1 | some date1 
some name3 | some amount3 | some pid3 | some product name3 | some date3 

是否可以使用SQL查詢來做到這一點,或者我應該試着與我的客戶端語言PHP做呢?

+0

其中'加入Query'?應該是table3連接colum IS NULL – Noman

回答

1

鬱可使用以下查詢:

SELECT t1.*, t2.* 
FROM table1 AS t1 
JOIN table2 AS t2 ON t1.product_id = t2.product_id 
LEFT JOIN table3 AS t3 ON t3.product_id = t2.product_id AND t1.total_amount = t3.total_amount 
WHERE t3.product_id IS NULL 

上述查詢連接table1table2現場product_id並篩選出記錄的情況下,存在具有相同product_idtotal_amount值匹配的記錄中table3

1

的直接的方法是使用NOT EXISTSNOT IN

select t1.name, t1.total_amount, t1.product_id, t2.product_name, t1.date 
from t1 
join t2 on t2.product_id = t1.product_id 
where (t1.total_amount, t1.product_id) not in 
(
    select t3.total_amount, t3.product_id 
    from t3 
);