I have to left join one table (bonds) with two other tables (orders_bid, orders_ask). But both other tables must also have a condition between them (customer_id must be the same).
bonds
-----------
id
ticker
...
orders_bid
-----------
id
bonds_id
customer_id
price
...
orders_ask
-----------
id
bonds_id
customer_id
price
My approach is the following:
SELECT bonds.ticker, orders_bid.price, orders_ask.price FROM bonds
LEFT JOIN orders_bid ON bonds.id=orders_bid.bonds_id
LEFT JOIN orders_ask ON bonds.id=orders_ask.bonds_id
But this leads to result rows are getting mixed over different customers, as the customer_id is not respected between both joined tables. Something like...
WHERE orders_bid.customer_id=orders_aks.customer_id
...is additionally needed, but it must not be a WHERE statement as something like an outer join is needed (one side might be empty). What's the right way?
Try by adding it to the JOIN conditions.
SELECT bonds.ticker, orders_bid.price, orders_ask.price FROM bonds
LEFT JOIN orders_bid
ON bonds.id = orders_bid.bonds_id
LEFT JOIN orders_ask
ON bonds.id = orders_ask.bonds_id
AND orders_bid.customer_id = orders_ask.customer_id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.