Jump to content

Tricky MySQL query: join, union, subquery or other???


cubik

Recommended Posts

[pre]i have two tables:

 

table_1: customers

+-------------+-----------------+

| customer_id | name            |

+-------------+-----------------+

|          1 | Joe Doe        |

|          2 | Fred Hitman    |

|          3 | Sam Coolguy    |

|          4 | Jennifer Art    |

+-------------+-----------------+

 

table_2: orders

+-----------+-------------+--------+

| order_id  | customer_id | status |

+-----------+-------------+--------+

|        1 |          2 | Open  |

|        2 |          1 | Closed |

|        3 |          4 | Open  |

|        4 |          1 | Open  |

|        5 |          1 | Closed |

|        6 |          3 | Closed |

+-----------+-------------+--------+

 

i need a MySQL query that would return the following result:

 

+-------------+----------+--------+

| customer_id | order_id | status |

+-------------+----------+--------+

|          1 |        4 | Open  |

|          2 |        1 | Open  |

|          3 |    Null | Null  |

|          4 |        3 | Open  |

+-------------+----------+--------+

 

table_1 must return all the rows and

when table_2 must be filter on the column 'status' (where status = 'Open') and then be 'join' to table_1

Null should be displayed if  customer_id doesn't exist in table_2 or exist but 'status' != 'Open'

 

it shouldn't be that complicated but i couldn't find anything similar to my problem.

 

Any idea would be greatly appreciated.

 

Thank you.

 

 

 

[/pre]

Link to comment
Share on other sites

[pre]

it doesn't work, if do :

 

select * from customers as c

left join orders as o ON c.customer_id = o.customer_id

where o.status = 'Open'

 

then the customer_id #3 is not in the result.

 

i need ALL the customers in the result set but with Null data if the clause on table_2 is not filled.

 

Thank you anyway. :)

[/pre]

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.