MySQL 优化过多的 WHERE 条件。

huangapple go评论58阅读模式
英文:

mysql optimize too many where conditions

问题

以下是翻译好的部分:

故事:我有两个学生表格。我需要为表 A 中的每个学生找出是否存在表 B 中的某个年龄更小且姓名相同的学生。

表 A(不是真实表格,可能是用户输入)

id 姓名 年龄
0 12
1 杰克 13
2 汤姆 23

表 B

id 姓名 年龄
0 14
1 吉尔 10
2 蒂姆 8
3 杰克 12

这是我当前的 SQL 查询:

select * from  where 姓名= and 年龄<12 or 姓名=杰克 and 年龄<13 ......

假设我需要过滤匹配输入筛选条件(表 A)的行,而 WHERE 关键字后面可能会跟随 1000 个以上的条件,将姓名和年龄成对组合。我尝试使用 MyBatis 的 foreach 生成查询,但效率非常低。如何优化上述查询?

英文:

the story: i have 2 tables of students. i need to find for every student in table A whether there is some student in table B that is younger and has the same name.

TABLE A (not real table, could be user input)

id name age
0 jim 12
1 jack 13
2 tom 23

TABLE B

id name age
0 jim 14
1 jill 10
2 tim 8
3 jack 12

this is my current sql query:

select * from table where name=jim and age&lt;12 or name=jack and age&lt;13 or ......

say i have to filter out the rows that match the input filter conditions(table A), and the where keyword could be followed by 1000 more conditions combining name and age in pair. I tried this and could generate query using mybatis foreach, but the efficiency is very low. how to optimize the above query?

答案1

得分: 1

从表A中选择tableA.*
从tableA中选择
在tableA上使用内连接,连接条件为tableA.name = tableB.name并且tableA.age > tableB.age
英文:
SELECT tableA.* 
  FROM tableA 
  INNER JOIN tableB ON tableA.name = tableB.name and tableA.age &gt; tableB.age

see: DBFIDDLE

You only need fixed comparsons when you need to find only studends that did not pass the age of 100 (WHERE age&lt;100)

Using tableA.name = tableB.name will compare the name in tableA with the name in tableB

答案2

得分: 1

尝试这样做:

SELECT * 
  FROM StudentsA 
  JOIN StudentsB ON StudentsA.name = StudentsB.name
     WHERE StudentsA.age > StudentsB.age

如果在(name,age)name上定义索引,它将更快且性能更好!

英文:

Try this:

SELECT * 
  FROM StudentsA 
  JOIN StudentsB ON StudentsA.name = StudentsB.name
     WHERE StudentsA.age &gt; StudentsB.age

If you define index on (name,age) Or name it will be faster and more performant!

huangapple
  • 本文由 发表于 2023年3月7日 22:25:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定