如何在 MYSQL 中组合多个 true/false 行

发布于 2024-10-03 12:51:06 字数 742 浏览 0 评论 0原文

我有一个对包含各种真/假列的表进行联接的查询。 我可以强制执行 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仙女 2024-10-10 12:51:07

当有 1 时您需要 1,如果没有则需要 0,因此 MAX(flag) 就足够了。

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文