2016-06-01 13 views
1

Ich habe 3 MySQL-Tabellen, um Daten von ihnen abzurufen.Kombinieren Werte von 3 verschiedenen MySQL-Tabelle, Join Tabelle 1 und Tabelle 2 und überprüfen, ob Tabelle 3 Werte in diesem Join bestehen

tabelle1 enthält die Zeilen:

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 

und table2:

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

und table3:

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

ich inner bin mit Verbindung zwischen Tabelle1 und Tabelle 2 mit ihrer product_id zu Werte wie folgt auflisten:

Aber ich möchte Zeilen in Join-Tabellenliste nicht zeigen, wenn total_amount und product_id von table3 gleiche Werte mit total_amount und product_id von table1 hat.

Deshalb möchte ich meine Ausgabe wie:

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 

Ist es möglich, dies mit SQL-Abfrage zu tun, oder sollte ich versuchen, es mit meinem Client-Seite Sprache PHP zu tun?

+0

wo 'Registriert Query'? sollte Tabelle3 Join colum IS NULL sein – Noman

Antwort

1

Yu können Sie die folgende Abfrage verwenden:

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 

Die obige Abfrage verbindet table1 und table2 auf dem Feld product_id und filtert Datensätze, falls es einen passenden Datensatz in table3 ist die gleiche product_id und total_amount Werten.

1

Der gerade Weg nach vorn ist NOT EXISTS oder NOT IN zu verwenden:

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 
);