V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
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
toomoy
V2EX  ›  MySQL

求 mysql 查询 sql

  •  
  •   toomoy · 2022-08-29 20:38:27 +08:00 · 1649 次点击
    这是一个创建于 576 天前的主题,其中的信息可能已经有所发展或是发生改变。
    id a b c d e
    1 a1 b1 c1 d1 e1
    2 a2 b2 c2 d2 e2

    我想要匹配 a-e 来查询列,有 5 个字段能匹配到 3 就行,比如,a=a1 and b=b2 and c=c1 and d=d2 and e=e1,因为 id=1 能匹配到 3 个字段就能查到,请问大佬,sql 怎么写? 不知道表达得是否清楚

    6 条回复    2022-08-30 11:31:44 +08:00
    akira
        1
    akira  
       2022-08-29 20:55:48 +08:00
    初级写法,直接上 条件组合
    (a = a1 and b = b1 and c = c1 ) or
    (a = a1 and b = b1 and d = d1) or
    (a = a1 and b = b1 and d = e1) or
    akira
        2
    akira  
       2022-08-29 21:00:51 +08:00   ❤️ 2
    中级写法,先分别 计算 每一行的 a-e 是否和你输入的一致,然后汇总看结果

    select * , `cal_a` + cal_b + cal_c + cal_d + cal_e `cal` from
    (
    select
    id ,
    if(a = a1, 1, 0) `cal_a`,
    if(b = b1, 1, 0) `cal_b`,
    if(c = c1, 1, 0) `cal_c`,
    if(d = d1, 1, 0) `cal_d`,
    if(e = e1, 1, 0) `cal_e`,
    ...
    ) a
    where `cal` >=3
    wxf666
        3
    wxf666  
       2022-08-29 23:29:25 +08:00
    这样?这要求 a b c d e 都为 NOT NULL ,且这会扫全表

    select *
      from ...
    where (a=a1) + (b=b2) + (c=c1) + (d=d2) + (e=e1) >= 3
    wolfie
        4
    wolfie  
       2022-08-30 09:35:16 +08:00
    @akira
    #2 写法,分页场景也会全表。
    xuanbg
        5
    xuanbg  
       2022-08-30 10:31:36 +08:00
    无论怎么写 SQL ,全表扫描跑不了。
    laqow
        6
    laqow  
       2022-08-30 11:31:44 +08:00
    如果 abcde 都有索引一楼应该比较好吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3247 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:42 · PVG 19:42 · LAX 04:42 · JFK 07:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.