GuitarGod Posted November 7, 2013 Share Posted November 7, 2013 Hi all, I'm not terribly good when it comes to SQLs, so forgive me if this seems like a dumb question. I have 3 tables (orders, non_customers and customers). Both the non_customers and customers table have a field in them called 'details'. In the orders table, I have a field called 'customer_type'. What I'm trying to convey is that if the 'customer_type' value is 0, then I would like the 'details' field pulled from the non_customers table, where as if the 'customer_type' value is 1, I'd like the 'details' field pulled from the customers table. SELECT o.*, n.*, c.* FROM orders o LEFT JOIN non_customers n ON o.customer_type = 0 LEFT JOIN customer c ON o.customer_type = 1 The code above doesn't seem to 'collate' the tables, it seems to return all of the orders, then all of the customer details. Any help is appreciated Regards. Quote Link to comment https://forums.phpfreaks.com/topic/283707-joiningif-3-tables/ Share on other sites More sharing options...
Barand Posted November 8, 2013 Share Posted November 8, 2013 Does the order table have a customer id to relate to the other tables? If they are a non_customer is there still a customer ID. How about sharing your table structures Quote Link to comment https://forums.phpfreaks.com/topic/283707-joiningif-3-tables/#findComment-1457469 Share on other sites More sharing options...
GuitarGod Posted November 8, 2013 Author Share Posted November 8, 2013 Hi Barand, Yes both the customers and non_customers table have a customer ID. Regards. Quote Link to comment https://forums.phpfreaks.com/topic/283707-joiningif-3-tables/#findComment-1457512 Share on other sites More sharing options...
Solution Barand Posted November 8, 2013 Solution Share Posted November 8, 2013 try $sql = "SELECT o.ord_id, o.customer_type, CASE customer_type WHEN 1 THEN c.details WHEN 0 THEN nc.details END as details FROM orders o LEFT JOIN non_customer nc ON o.cust_id = nc.cust_id LEFT JOIN customer c ON o.cust_id = c.cust_id"; Quote Link to comment https://forums.phpfreaks.com/topic/283707-joiningif-3-tables/#findComment-1457559 Share on other sites More sharing options...
GuitarGod Posted November 8, 2013 Author Share Posted November 8, 2013 If memory serves, this isn't the first timed you've helped me and got the answer spot on. Many thanks, sincerely Quote Link to comment https://forums.phpfreaks.com/topic/283707-joiningif-3-tables/#findComment-1457581 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.