如何在 MYSQL 中组合多个 true/false 行
我有一个对包含各种真/假列的表进行联接的查询。 我可以强制执行 DISTINCT & GROUP BY 确保只返回单个唯一行,但是 true/false 行的行为不可预测,例如:
**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
这给了我包含 loc 名称列表的行。然而,标志列有时会返回多行,我想要做的是合并这些行,这样如果有多个行,并且它们同时包含 0 和 1,则查询将仅返回标志设置为 1 的一行。如果多个行rows 包含 0,它将为该行返回 0... 我尝试使用 GROUP BY name,它会返回唯一的行,但是我注意到,对于在标志列中同时设置了 0 和 1 的重复行,它将返回 0?
任何帮助表示赞赏
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当有 1 时您需要 1,如果没有则需要 0,因此 MAX(flag) 就足够了。
As you want 1 when there is a 1, and 0 if not, a MAX(flag) should suffice.