加入 2 个表会创建不需要的重复数据

joing 2 tables creates unwanted duplicate data

我不知道如何加入 2 tables。 我只想加入另一个 table 的 1 列,但添加它会在 table 中创建大量重复数据。

第一个table:"devices":

id | device_type | open_ticket_count | device_owner 
1  | tablet      | 1                 | bob
2  | smartphone  | 0                 | 
3  | printer     | 1                 | sally

第二个table:"tickets":

id | due_at
1  | 25/12/2016
2  | 
3  | 13/11/2016

我想加入他们所以是这样的:

id | device_type | open_ticket_count | device_owner | due_at
1  | tablet      | 1                 | bob          | 25/12/2016
2  | smartphone  | 0                 |              |
3  | printer     | 1                 | sally        | 13/11/2016

我该怎么做?

此代码创建了 292 行,但只有 3 台设备和 2 张工单打开?

SELECT devices.id, devices.device_type, devices.open_ticket_count, devices.primary_owner_name AS Assigned_Owner, tickets.id, tickets.due_at 

FROM devices CROSS JOIN tickets where devices.user_tag = '|pool devices|' AND tickets.due_at

关于如何显示的任何想法

具有 due_at 列的所有设备?

安迪,试试

SELECT devices.id, devices.device_type, devices.open_ticket_count, devices.device_owner AS Assigned_Owner, tickets.due_at
FROM devices INNER JOIN tickets
ON devices.id = tickets.id
WHERE due_at IS NOT NULL

尽管这假定 tickets.due_at 列对于 id = 2

所在的行将是 null

但是,如果您排除设备 table 中具有 open_ticket_count = 0 的行,您将得到相同的结果(假设如果没有匹配的 ticket[,则该值为零=22=] 行

SELECT D.id, D.device_type, D.open_ticket_count, D.device_owner, T.due_at 
FROM Devices D LEFT OUTER JOIN Tickets T 
ON D.id = T.id

您想要显示左侧列的所有行,因此您需要LEFT OUTER JOIN