我想要加入4个表。
Customers
Traffic
Average
Live
我想将这些表的连接数据插入“详细信息”表。 表格之间的关系如下: Traffic,Average和Live表中的每一个都有一个“cid”,它是“Customers”表的主键:
Traffic.cid = Customers.id
Average.cid = Customers.id
Live.cid = Customers.id
我写的查询在这里:
INSERT INTO Details
(
cid, Customer_Name, Router_Name,
Traffic_Received,
Average_Received,
Live_Received,
date
)
(
SELECT Customers.id AS cid, Customers.name AS Customer_Name, Traffic.Router_Name,
Traffic.Received,
Average.Received,
Live.Received,
Traffic.date
FROM Customers
INNER JOIN Traffic ON Customers.id=Traffic.cid
INNER JOIN Average ON Customers.id=Average.cid
INNER JOIN Live ON Customers.id=Live.cid
WHERE Traffic.date='2015-06-08'
)
但结果会有重复的行。我将JOIN
更改为LEFT JOIN
和RIGHT JOIN
。但结果没有改变。
如何在Details
表中没有重复的行?
答案 0 :(得分:0)
你能试试吗
INSERT INTO Details
(
cid, Customer_Name, Router_Name,
Traffic_Received,
Average_Received,
Live_Received,
date
)
(
SELECT Customers.id AS cid,
Customers.name AS Customer_Name,
Traffic.Router_Name,
Traffic.Received,
Average.Received,
Live.Received,
Traffic.date
FROM Customers
INNER JOIN Traffic ON Customers.id=Traffic.cid
INNER JOIN Average ON Customers.id=Average.cid
INNER JOIN Live ON Customers.id=Live.cid
WHERE Traffic.date='2015-06-08'
GROUP BY
cid,
Customer_Name,
Traffic.Router_Name,
Traffic.Received,
Average.Received,
Live.Received,
Traffic.date
)
答案 1 :(得分:0)
SELECT Customers.id AS cid, Customers.name AS Customer_Name, Traffic.Router_Name,
Traffic.Received,
Average.Received,
Live.Received,
Traffic.date
FROM Customers
LEFT JOIN Traffic ON Customers.id=Traffic.cid
LEFT JOIN Average ON Traffic.cid=Average.cid
LEFT JOIN Live ON Average.cid=Live.cid
WHERE Traffic.date='2015-06-08'
答案 2 :(得分:0)
使用LEFT JOIN
,即使没有与Traffic
对应的记录,您也会加入表格(例如Customers.id
),在这种情况下,您将获得此表中没有匹配记录的列的null
值。
使用RIGHT JOIN
,即使Customers
中没有相应的记录,您也会从联接表中获取所有记录。
但是,JOIN
的类型不是问题。如果您在结果中获得重复记录,则表示您要加入的表中有多个匹配记录。例如,Traffic
中可能有多条记录与cid
相同。使用SELECT DISTINCT
删除重复项,或者如果您对这些重复项的汇总感兴趣,请使用汇总函数,例如count()
或sum()
和GROUP BY
子句,例如GROUP BY Traffic.cid
。
如果你仍然有重复项,那么检查以确保它们确实是重复的 - 我建议一个或多个列实际上是不同的。