我有以下带有一些示例数据的 mysql 表。
1) 表:ai_shipment
+----+---------------------+---------------------+------------------+
| id | booking_date | loading_date | container_number |
+----+---------------------+---------------------+------------------+
| 1 | 2012-08-03 00:00:00 | 2012-08-04 00:00:00 | ABB987987BBC6 |
| 2 | 2012-08-05 00:00:00 | 2012-08-07 00:00:00 | BHJKKU78786GH |
+----+---------------------+---------------------+------------------+
2)表:ai_purchase_item
+----+---------+----------+-----------+-----------+
| id | item_id | quantity | cost | rate |
+----+---------+----------+-----------+-----------+
| 1 | 1 | 50 | 1200.0000 | 1355.0000 |
| 2 | 2 | 20 | 550.0000 | 675.0000 |
| 3 | 4 | 70 | 70.0000 | 70.0000 |
| 4 | 6 | 90 | 90.0000 | 90.0000 |
| 5 | 7 | 80 | 80.0000 | 80.0000 |
+----+---------+----------+-----------+-----------+
3) 表:shipping_purchase_item
+----+-------------+------------------+
| id | shipment_id | purchase_item_id |
+----+-------------+------------------+
| 1 | 1 | 2 |
| 2 | 2 | 3 |
+----+-------------+------------------+
基本上,我将所有购买的物品详细信息存储在 中ai_purchase_item
,ai_shipment
存储运输详细信息,并ai_shipment_purchase_item
存储已运输物品的记录。
我想做的是,我想从中选择所有ai_purchase_item
未发货的记录。这意味着外键不应该存在于ai_shipment_purchase_item
.
参考上面的记录,我期望得到的结果是。
+----+---------+----------+-----------+-----------+
| id | item_id | quantity | cost | rate |
+----+---------+----------+-----------+-----------+
| 1 | 1 | 50 | 1200.0000 | 1355.0000 |
| 4 | 6 | 90 | 90.0000 | 90.0000 |
| 5 | 7 | 80 | 80.0000 | 80.0000 |
+----+---------+----------+-----------+-----------+
我尝试过这样的事情(我知道 sql 查询不正确)
SELECT
pi.id,
pi.item_id,
pi.quantity,
pi.cost,
pi.rate
FROM
ai_purchase_item pi
JOIN
ai_shipment_purchase_item spi ON spi.purchase_item_id = pi.id
WHERE NOT EXISTS (SELECT spi.purchase_item_id WHERE spi.purchase_item_id = pi.id)
谢谢你。