how to combine multiple true/false rows in MYSQL
I have a query with a join on a table containing various true/false columns. I can enforce DISTINCT & GROUP BY to ensure only single unique row gets returned, however the true/false rows do not behave predictably, example:
**Table 1**
loc_id name
-------------
1 a
2 b
3 c
4 d
**Table 2**
prod_id loc_id value
-------------
1 1 abc
2 1 bcd
3 1 def
4 2 fgh
**Table 3**
prod_id flag
-------------
1 0
2 0
3 1
4 1
SELECT DISTINCT name, flag from table1
LEFT JOIN table3 ON table3.prod_id = table2.prod_id
LEFT JOIN table2.loc_id=table1.loc_id
This gives me rows containing a list of loc names. However the flag column returns multiple rows sometimes, what i would like to do is combine these rows so that if there is more than one, and they contain both 0 and 1 the query will return only one row with flag set to 1. If multiple rows contain 0, it will return 0 for that row... I tried using GROUP BY name, which returns unique rows back, however i have noticed that for duplicate rows having both 0 and 1 set in the flag column it will return 0?
开发者_开发技巧Any help appreciated
As you want 1 when there is a 1, and 0 if not, a MAX(flag) should suffice.
SELECT name, MAX(flag) from table1
LEFT JOIN table3 ON table3.prod_id = table2.prod_id
LEFT JOIN table2.loc_id=table1.loc_id
GROUP BY name
精彩评论