我目前有以下查询:
select title,location,categorie,division,
reference.description as CA
from emploi
left join reference on emploi.categorie = reference.code_ref
where id_type = 'CA' and emploi.status ='1'
我有第二个查询,它是相同的,但从引用表中获取不同的值:
select title,location,categorie,division,
reference.description as DI
from emploi
left join reference on emploi.division = reference.code_ref
where id_type = 'DI' and emploi.status ='1'
有没有办法执行这两个查询?
我认为这是类似于以下内容的内容,但它显然不起作用:
select title,location,categorie,division,
reference.description as DI, reference.description as CA
from emploi
(left join reference on emploi.division = reference.code_ref
where id_type = 'DI')
(left join reference on emploi.categorie = reference.code_ref
where id_type = 'CA')
where emploi.status ='1'
谢谢!
注意:emploi 表中的每个条目都有一个部门和类别列,它们都需要映射到同一行上的单独条目
编辑:
对于那些感兴趣的人来说,这是可行的解决方案:
select title,location,categorie,division,
r.description as DI, r1.description as CA
from emploi
left join reference r on emploi.division = r.code_ref
and r.id_type = 'DI'
left join reference r1 on emploi.categorie = r1.code_ref
and r1.id_type = 'CA'
where emploi.status ='1'
最佳答案
你可以试试这个:
select title,location,categorie,division,
r.description as DI, r1.description as CA
from emploi
left join reference r on emploi.division = r.code_ref
left join reference r1 on emploi.categorie = r1.code_ref
where emploi.status ='1'
and id_type in ('CA', 'DI')
目前,您的语法不正确,因为您在 左连接
中使用了两次 where
子句。还将别名放入表中并使用这些别名来获取列名称
类似的东西
select tablename.title,tablename.location,tablename.categorie,tablename.division,
r.description as DI, r1.description as CA
from emploi
left join reference r on emploi.division = r.code_ref
left join reference r1 on emploi.categorie = r1.code_ref
where emploi.status ='1'
and id_type in ('CA', 'DI')
注意:使用正确的表名称代替上面的tablename
编辑:-
如果您不想使用 IN 子句,那么
select title,location,categorie,division,
r.description as DI, r1.description as CA
from emploi
left join reference r on emploi.division = r.code_ref
and r.id_type = 'DI'
left join reference r1 on emploi.categorie = r1.code_ref
and r1.id_type = 'CA'
where emploi.status ='1'
假设id_type
是emploi
的一列
关于mysql - 来自同一个引用表的多个 sql 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25745209/