我有3个MySQL表来检索它们的数据。
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
和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
和table3:
id | total_amount | product_id
-------------------------------
1 | some amount | some pid
2 | some amount2 | some pid2
我正在使用table1和table2之间的内部联接及其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 Query执行此操作,还是应该尝试使用客户端语言PHP?
答案 0 :(得分:1)
Yu可以使用以下查询:
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
以上查询在字段table1
上加入table2
和product_id
,并在table3
中具有相同product_id
的匹配记录时筛选出记录和total_amount
值。
答案 1 :(得分:1)
直截了当的方法是使用NOT EXISTS
或NOT 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
);