如何优化我的查询加入Mysql中的两个表

时间:2014-04-09 08:21:06

标签: mysql sql

我的要求如下

  

SQL1:sel Names,Table1中的Numbers,其中condition = FilterName

the output of this will be like:
    aa,11
    bb,22
     cc,33

SQL2:我需要写一个像这样的SQL

 Sel * from table2 where condition = 'Something' 
         And names & Numbers in ([aa,11],[bb,22],[cc,33])

我写了像

这样的查询
Select * from table2 where condition = 'SOmething' 
         And names in (select Names from Table1 where condi = 'FilterName')
         And Numbers in (select Numbers from Table1 where condi = 'FilterName')

还有其他更好的方法来编写此查询吗?我不能在这里使用程序

2 个答案:

答案 0 :(得分:3)

您可以尝试在此处使用JOIN:

Select table2.* from table2
join table1 on table2.names = table1.names and table2.numbers = table1.numbers
where table1.condi = 'FilterName'
and table2.condition = 'Something'

我希望这有帮助!

答案 1 :(得分:2)

根据我对问题的解释,这样的事情应该这样做:

SELECT *
FROM table2 t2
JOIN table1 t1 ON t1.Names = t2.names AND t1.Numbers = t2.numbers
WHERE t1.condi = 'FilterName'
AND t2.condition = 'Something'

MySQL确实有(a,b,c) IN ((a1,b1,c1),(a2,b2,c2)...)的语法,但我还没有找到一种方法来使用索引,所以它不是很有用。