mysql - 如何在同一列的两个条件上使用联接进行选择

标签 mysql sql

我正在努力实现这样的目标。

id  tag   name
1   foo    name
1   bar    name
2   foo    name
2  foss   name

我试图做的是。

select id, group_concat(distinct tag) as tag, group_concat(distinct name) as name
where tag = "foo" or tag = "bar" group by id;

我得到的,

id     tag       name
1    foo, bar  name
2    foo, foss name

但是,我想要的只是如果标签是“foo”和“bar”对于相同的id,然后打印,这应该给出这样的输出。

id     tag       name
1     foo, bar   name

我这样做了,因为它可以通过使用 AND 在 JAVA 或 C++ 等编程语言中工作。结果为空..

select id, group_concat(distinct tag) as tag, group_concat(distinct name) as name
where (tag = "foo" and tag = "bar") group by id;

最佳答案

我认为你想要一个group by和一个having:

select id, group_concat(distinct tag) as tag,
       group_concat(distinct name) as name
from t
where tag in ('foo', 'bar')
group by id
having count(distinct tag) = 2;

作为注释。我熟悉的任何编程语言对于 tag = 'foo' 和 tag = 'bar' 都会返回 false,因为 tag 可以有一个值或另一个值,但不能同时有两个值。

关于mysql - 如何在同一列的两个条件上使用联接进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31600788/

相关文章:

php - JOIN - 选择具有不同于 COUNT 标准的列/详细信息

jquery - Hive 查询到组

php - mysql查询计数和求和

php - 使用来自 MYSQL 的数据动态填充 Google 折线图

mysql - 在加入冗余和得到

java - 在 mysql 查询中传递 java 字符串变量

SQL 在 WHERE 子句中合并

php - Laravel 中按多态关系对数据库结果进行排序

php - Magento - 管理员缺少 CSS

mysql - 使用 LIKE 条件用 sql 搜索德语字符