Jump to content

Joining/if 3 tables


GuitarGod
Go to solution Solved by Barand,

Recommended Posts

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 ;D

 

Regards.

Link to comment
Share on other sites

  • Solution

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";

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.