开发者

MySQL - complicated LEFT JOIN

I have that one-to-many relationship going here. Plus, not all "primary" records will have a joined record in the second database table.

Here are my tables:

tbl_customers tbl_addresses

A customer record in tbl_customers can obviously have many addresses, in the tbl_addresses table.

Here's my dilemma. There are many customer records with several addresses, and I assign one of those address records as the "main" address for a customer record. This is simply a single column called: primaryAddress. The value will be a number 1, if that address record is the main address.

So here is my query:

SELECT c.customername, a.state 
FROM `tbl_customers` c
LEFT JOIN `tbl_addresses` a ON c.customerid = a.customerid

That query will result 开发者_开发技巧in duplicate records for any customer with more than 1 address. If I add a little more to the LEFT JOIN:

SELECT c.customername, a.state 
FROM `tbl_customers` c
LEFT JOIN `tbl_addresses` a ON c.customerid = a.customerid AND a.primaryAddress = 1

This produces no results, even when I see in the database there are plenty of address records with primaryAddress = 1.

So I'm thinking my query is wrong.

Can someone see what I'm missing?


To anyone who happens to land on this page looking for a solution:

THIS DOES NOT PROPERLY ANSWER THE QUESTION

The user was able to find the cause after discussing the problem here. Turns out he had a typo on his original code. The second block of SQL code posted on the question is correct, and should give the expected results. +1 for user JoeStefanelli for pointing this out.

Please read the comments for details. My original answer is below. Now I see I should have deleted it, instead of trying to amend it, as soon I realized it was flawed. At least the discussion helped the user find a solution...


My original answer:

You are almost there. Add a.primaryAddress = 1 to the WHERE clause instead.

EDIT

Not sure if this will exclude costumers with zero addresses from the results...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜