mysql - 来自同一个引用表的多个 sql 连接

标签 mysql sql

我目前有以下查询:

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_typeemploi的一列

关于mysql - 来自同一个引用表的多个 sql 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25745209/

相关文章:

html - 如何创建一个与基本数据库交互的简单 Web 应用程序?

php - 使用给定的变量名称将前三个结果保存在 while 循环中?

sql - Postgres vs oracle 做 100 万 sqrts 我做错了吗?

javascript - 如何从过滤函数改进自制SQL语法?

mysql - SQL:对 COUNT 和 GROUP 求和以合并查询

php - 将重复项合并到一行并使用 php 求和

mysql - 如果不存在则选择插入添加或更新

php - 识别具有两个帐户的用户

java - 荒谬的Java多线程和MySQL同步

sql语句在decode子句中