So, just to ensure I understand you correctly, you want to only show the rows from the abd_table if:
IF that’s correct, then your query would be something like this
SELECT a.date
, a.quantity
, a.total_cost
, a.user_name
, a.product_name
, a.unique_id
, a.price
, nw.order_id
, nw.payment_status
FROM order_table AS nw
LEFT JOIN order_detail_table as o ON o.unique_id = nw.unique_id
INNER JOIN abd_table AS a ON a.unique_id = o.unique_id
WHERE nw.payment_status='PENDING'
AND (o.order_id IS NULL OR
(a.product_name <> o.product_name OR
a.price <> o.price OR
a.quantity <> o.quantity OR
a.total_cost <> o.total_cost))
That being said, you have a real normalization problem in your database, and you’re going to run into issues trying to maintain this the longer you go. Just some of the issues I see:
- You’re using a field name as a primary key on one table and a secondary key on another.
- You’ve got duplicate fields across multiple tables. This can cause data to get out of sync (which you’ve obviously found)
IF you’re not too far down the rabbit hole with this project, I would suggest tweaking your database structure to something much more streamlined.
Some notes:
- unique_id will now be the key JUST for the table it’s on. In other words, unique_id on abd_table is NOT the same as unique_id on order_table
- if you see *table_id, that’s the foreign key to the appropriate table. For example, abd_table_id will be equal to a unique_id on abd_table
- I’m assuming that order_id is just a “user friendly” order number and not just a sequential number - if it is just a sequential number, get rid of it and use the unique_id
- total_cost COULD be derived (in other words calculated), but I left it here for now…
abd_table
unique_id
product_name
price
order_table
unique_id
order_id (see note above)
order_date
payment_status
order_detail_table
unique_id
order_table_id
abd_table_id
quantity
total_cost (see note above)
So to select the full order details, it would be something like this:
SELECT ot.order_id
, ot.payment_status
, ot.order_date
, abd.product_name
, abd.price
, od.quantity
, (abd.price * od.quantity) AS total_cost
FROM order_table AS ot
JOIN order_detail_table AS od ON ot.unique_id = od.order_table_id
JOIN abd_table adt ON abd.unique_id = or.abd_table_id
WHERE ot.payment_status = 'PENDING'