求 mysql 查询 sql

2022-08-29 20:38:27 +08:00
 toomoy
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 怎么写? 不知道表达得是否清楚

1685 次点击
所在节点    MySQL
6 条回复
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
2022-08-29 21:00:51 +08:00
中级写法,先分别 计算 每一行的 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
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
2022-08-30 09:35:16 +08:00
@akira
#2 写法,分页场景也会全表。
xuanbg
2022-08-30 10:31:36 +08:00
无论怎么写 SQL ,全表扫描跑不了。
laqow
2022-08-30 11:31:44 +08:00
如果 abcde 都有索引一楼应该比较好吧

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

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

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

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

© 2021 V2EX