请教一条 SQL 写法

2020-02-18 16:08:37 +08:00
 ZPPP
表结构如下:
id name
1 A
2 A
2 B
3 A
3 B
3 C
查询 name 仅含 A,B,得到结果 id 为 2。
3721 次点击
所在节点    MySQL
15 条回复
oneisall8955
2020-02-18 16:13:15 +08:00
。。。
execute
2020-02-18 16:18:54 +08:00
没有附加条件么?
那 :where id = 2
shyrock
2020-02-18 16:19:37 +08:00
这。。。作业?好奇 lz 咋写的 SQL
speedofstephen
2020-02-18 16:21:54 +08:00
select H1.id from
(select id, count(name) as cnt from T where name in ('A' ,'B') group by id) H1
inner join
(select id, count(name) as cnt from T group by id) H2
where H1.id = H2.id and H1.cnt = H2.cnt;
speedofstephen
2020-02-18 16:23:19 +08:00
错了 好像还得加上 where H1.cnt=2
shyrock
2020-02-18 16:24:22 +08:00
select distinct(id) from T MINUS select distinct(id) from T where name in ('C','D',...)
ZPPP
2020-02-18 16:44:23 +08:00
@shyrock 表中不存在 C 和 D。
@speedofstephen 表中含有千万条数据,内连接 H2 会比较慢。
taotaodaddy
2020-02-18 17:14:11 +08:00
考虑一下 concat ?效率不知
ebony0319
2020-02-18 17:15:18 +08:00
select * from table t where name in ('A','B') and 2=(
select count(1) from table t1 where t1.name=t.name
)
这里的 2 为('A','B') 的长度。
ebony0319
2020-02-18 17:16:06 +08:00
修改一下:
select * from table t where name in ('A','B') and 2=(
select count(1) from table t1 where t1.id=t.id
)
这里的 2 为('A','B') 的长度。
ZPPP
2020-02-18 21:23:53 +08:00
@ebony0319 有个 id 对应 A 和 C 也会返回
ZPPP
2020-02-18 22:37:50 +08:00
@speedofstephen 感谢,是正解。
turan12
2020-02-19 00:20:28 +08:00
请楼主独立完成作业。。。
zhuzhibin
2020-02-19 01:21:21 +08:00
内联取交集?
alya
2020-02-19 10:28:29 +08:00
select
id
from t1
group by id
having collect_set(name) in (array("A","B"), array("B", "A"))

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/645565

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX