i have the following mysql tables with some sample data.
1) table: 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) table: 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) table: shipment_purchase_item
+----+-------------+------------------+
| id | shipment_id | purchase_item_id |
+----+-------------+------------------+
| 1 | 1 | 2 |
| 2 | 2 | 3 |
+----+-------------+------------------+
basically i am storing all the purchased items details in ai_purchase_item, ai_shipment stores the shipping details, and ai_shipment_purchase_item stores records of items that is shipped.
what i am trying to do is, i want to select all records from ai_purchase_item that is not shipped. which means the foreign key should not exist in ai_shipment_purchase_item.
with reference to above records the result i am expecting to be fetched is.
+----+---------+----------+-----------+-----------+
| 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 |
+----+---------+----------+-----------+-----------+
i tried something like this (i know the sql query is not proper)
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)
thank you.
There are three common approaches for finding values present in one table but missing in another in MySQL:
LEFT JOINNOT EXISTSNOT INHere’s the approach using
NOT EXISTS:And here’s a
LEFT JOIN:And here’s
NOT IN:The following article by Quassnoi compares the performance of each of these approaches:
The conclusion is: