连接子查询的等效项

时间:2016-06-04 12:30:35

标签: mysql sql

下面的sql语法的连接等价物是什么:

select * from legislative where id in 
  (select id_legislative from legislative_domeniu where id_domeniu in 
    (select domeniu_id from account_domeniu  where account_id=$user_id)
  ) 
order by data_modified desc limit 12

1 个答案:

答案 0 :(得分:1)

它可能看起来像这样:

select l.*
from legislative l join
     legislative_domeniu ld
     on l.id = ld.id_legislative join
     account_domeniu d
     on ld.id_domeniu = d.domeniu_id
where d.account_id = $user_id
order by l.data_modified desc
limit 12;

“可能”取决于基础表生成的重复项。您的结构看起来像两个实体之间的联结表,这通常没有重复。

如果这是一个问题,那么最简单的方法是select distinct

select distinct l.*
from legislative l join
     legislative_domeniu ld
     on l.id = ld.id_legislative join
     account_domeniu d
     on ld.id_domeniu = d.domeniu_id
where d.account_id = $user_id
order by l.data_modified desc
limit 12;