多重连接中的哪种 JOIN 类型

Which JOIN type in multiple joins

我有 4 个 table 想加入。

  1. Customers
  2. Traffic
  3. Average
  4. Live

我想将这些 table 的连接数据插入到 "Details" table。 table之间的关系在这里: Traffic、Average 和 Live table 中的每一个都有一个 "cid",它是 "Customers" table:

的主键

我写的查询在这里:

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 JOINRIGHT JOIN。但结果没有改变。 我应该怎么做才能在 Details table 中没有重复的行?

你能试试这个吗

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

使用 LEFT JOIN,您将加入 table(例如 Traffic),即使没有对应于 Customers.id 的记录,在在这种情况下,您将从没有匹配记录的 table 中获得列的 null 值。

使用 RIGHT JOIN,您将获得加入的 table 中的每条记录,即使 Customers 中没有对应的记录。

不过,JOIN的类型不是这里的问题。如果您在结果中得到重复记录,那么这意味着在您要加入的 table 中有不止一条匹配记录。例如,Traffic中可能有不止一条记录具有相同的cid。使用 SELECT DISTINCT 删除重复项,或者如果您对这些重复项的聚合感兴趣,请使用聚合函数,例如 count()sum()GROUP BY 子句,例如GROUP BY Traffic.cid.

如果您仍然有重复项,请检查以确保它们确实是重复项 - 我建议一列或多列实际上是不同的。