在一个表中显示条目列表,在多/链接表中没有条目

时间:2019-04-17 15:40:20

标签: mysql

我正在开发音乐节应用程序。我有三个表artistsvehiclesvehicleLink

artists是;

| id | name     |
|----|----------|
| 1  | Artist 1 |
| 2  | Artist 2 |
| 3  | Artist 3 |

vehicles是;

| id | type | reg  |
|----|------|------|
| 1  | Car  | REG1 |
| 2  | Van  | REG2 |
| 3  | Car  | REG3 |

vehicleLink是;

| id | artist_id | vehicle_id |
|----|-----------|------------|
| 1  | 1         | 1          |
| 2  | 1         | 2          |
| 3  | 2         | 3          |

我可以使用以下MySQL轻松显示所有艺术家车辆的列表;

SELECT v.id, v.type, v.reg, a.name AS artist_name
FROM vehicles v
JOIN vehicleLink l ON v.id = l.vehicle_id
JOIN artists a ON l.artist_id = a.id

这给;

| id | reg  | type | artist_name |
|----|------|------|-------------|
| 1  | REG1 | Car  | Artist 1    |
| 2  | REG2 | Van  | Artist 1    |
| 3  | REG3 | Car  | Artist 2    |

我现在需要一个列表,其中artist_id中还没有vehicleLink。例如,打印尚未向我们提供车辆详细信息的人员列表。

我已经搜索了StackOverflow和Google,但没有找到任何可行的方法,我只是直接在phpMyAdmin中尝试此操作。例如,添加以下WHERE NOT,返回0行;

where not exists (select 1 from artists where id = l.artist_id)

餐桌艺术家有id。 表格vehicleLink具有artist_id

我需要正确的查询以显示哪个artists.id没有出现在vehicleLink中,在这些示例中,哪个是Artist 3。

1 个答案:

答案 0 :(得分:1)

您应该尝试不要在车辆ID中使用

select  a.name AS artist_name, a.id AS artist_id 
from artists a where  a.id not IN (
  SELECT  a.id  
  FROM vehicles v
  JOIN vehicleLink l ON v.id = l.vehicle_id
  JOIN artists a ON l.artist_id = a.id

)