› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
ZPPP
V2EX  ›  MySQL

请教一条 SQL 写法

  •  
  •   ZPPP · Feb 18, 2020 · 5121 views
    This topic created in 2454 days ago, the information mentioned may be changed or developed.
    表结构如下:
    id name
    1 A
    2 A
    2 B
    3 A
    3 B
    3 C
    查询 name 仅含 A,B,得到结果 id 为 2。
    Supplement 1  ·  Feb 18, 2020
    表的数量级为千万 jibie
    15 replies  •  2020-02-19 10:28:29 +08:00
    itechify
    itechify
    Feb 18, 2020 via Android
    1
    。。。
    execute
    execute
    Feb 18, 2020
    2
    没有附加条件么?
    那 :where id = 2
    shyrock
    shyrock
    Feb 18, 2020
    3
    这。。。作业?好奇 lz 咋写的 SQL
    speedofstephen
    speedofstephen
    Feb 18, 2020❤️1
    4
    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
    speedofstephen
    Feb 18, 2020
    5
    错了 好像还得加上 where H1.cnt=2
    shyrock
    shyrock
    Feb 18, 2020
    6
    select distinct(id) from T MINUS select distinct(id) from T where name in ('C','D',...)
    ZPPP
    ZPPP
    OP
    Feb 18, 2020
    7
    @shyrock 表中不存在 C 和 D。
    @speedofstephen 表中含有千万条数据,内连接 H2 会比较慢。
    taotaodaddy
    taotaodaddy
    Feb 18, 2020 via Android
    8
    考虑一下 concat ?效率不知
    ebony0319
    ebony0319
    Feb 18, 2020
    9
    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
    ebony0319
    Feb 18, 2020
    10
    修改一下:
    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
    ZPPP
    OP
    Feb 18, 2020 via Android
    11
    @ebony0319 有个 id 对应 A 和 C 也会返回
    ZPPP
    ZPPP
    OP
    Feb 18, 2020
    12
    @speedofstephen 感谢,是正解。
    turan12
    turan12
    Feb 19, 2020
    13
    请楼主独立完成作业。。。
    zhuzhibin
    zhuzhibin
    Feb 19, 2020 via iPhone
    14
    内联取交集?
    alya
    alya
    Feb 19, 2020
    15
    select
    id
    from t1
    group by id
    having collect_set(name) in (array("A","B"), array("B", "A"))
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1843 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 09:21 · PVG 17:21 · LAX 01:21 · JFK 04:21
    ♥ Do have faith in what you're doing.