英文:
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<12 or name=jack and age<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 > 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<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 > StudentsB.age
If you define index on (name,age)
Or name
it will be faster and more performant!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论