I have got 3 tables.
Orders Clients Referrals
----- ----- -----
id id id
total_price name name
receiver_client_id status client_id
While adding order, sometimes the receiver is CLIENT, sometimes REFERRAL, so receiver_client_id can have both client_id or referral_id. Referrals are added by Clients, that’s why I store client_id in referrals table.
I want to get all the orders of a client who’s id is "15032" as well as it’s referrals orders in one query. Is it possible?
Sample data:
Orders Clients Referals
---- ---- ----
1, 350, 15032 15010, "Alex", 1 7809100, "Jay", 15010
2, 440, 16500 15011, "Jacob", 1 7809101, "Jean",15010
3, 210, 18023 15012, "Sam", 0 7809102, "Hew", 15011
4, 900, 15032 15032, "John", 1 7809123, "Aldo",15032
5, 330, 7809123 15040, "Sandy", 0 7809124, "Sew", 15032
Expected result:
1, 350, 15032
4, 900, 15032
5, 330, 7809123
2
Answers
Try the query below
Then you
UNION
the Clients and Referrals table first. This will get you orders from both clients and referralsAll you should need to do is UNION two tables together, one for the orders, and one for the referrals. To get the orders where the referral number links back to the client id, a JOIN will be needed: