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?
2
Answers
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 tableBTry this:
If you define index on
(name,age)
Orname
it will be faster and more performant!