MySQL在其中一个表的不同列上的两个表之间进行多个内部联接

时间:2015-01-21 07:44:56

标签: mysql sql join

transport

Id  | FirstLevSubcat | SecondLevSubcat | ThirdLevSubcat 
--------------------------------------------------------
 8  |   4            |   27            |  1418

categories

Id    | CategoriesUrl
--------------------
 4    |   cars          
 27   |   audi          
 1418 |   audi-100

查询是否使用categories表(没有inner join)就像

SELECT count(*) FROM transport
WHERE FirstLevSubcat = 4 AND SecondLevSubcat = 27 AND ThirdLevSubcat = 1418

尝试使用INNER JOIN

获得相同的结果
SELECT count(*) FROM transport main_table 
INNER JOIN categories cat_table_first ON cat_table_first.IdRows = main_table.FirstLevSubcat 
INNER JOIN categories cat_table_second ON cat_table_second.IdRows = main_table.SecondLevSubcat 
INNER JOIN categories cat_table_third ON cat_table_third.IdRows = main_table.ThirdLevSubcat 
WHERE 
cat_table_first.CategoriesUrl = 'cars' 
AND cat_table_second.CategoriesUrl = 'audi' 
AND cat_table_third.CategoriesUrl = 'audi-100' 

乍一看所有作品

但是这样的查询还好吗?可能会有所改善吗?

1 个答案:

答案 0 :(得分:1)

您的查询是正确的。您也可以通过以下方式完成:

SELECT count(*) FROM transport main_table 
INNER JOIN categories cat_table_first ON cat_table_first.IdRows = main_table.FirstLevSubcat and cat_table_first.CategoriesUrl = 'cars'
INNER JOIN categories cat_table_second ON cat_table_second.IdRows = main_table.SecondLevSubcat and cat_table_second.CategoriesUrl = 'audi' 
INNER JOIN categories cat_table_third ON cat_table_third.IdRows = main_table.ThirdLevSubcat and cat_table_third.CategoriesUrl = 'audi-100' 

您也可以使用3 EXISTS阻止来执行此操作。

SELECT count(*) FROM transport main_table 
WHERE 
EXISTS (SELECT NULL FROM categories WHERE main_table.FirstLevSubcat=categories.IdRows AND categories.CategoriesUrl ='cars') 
AND
EXISTS (SELECT NULL FROM categories WHERE main_table.SecondLevSubcat=categories.IdRows AND categories.CategoriesUrl ='audi') 
AND
EXISTS (SELECT NULL FROM categories WHERE main_table.ThirdLevSubcat=categories.IdRows AND categories.CategoriesUrl ='audi-100')