简体   繁体   English

使用 Mysql 的复杂 select 语句

[英]Complex select statment using Mysql

I dont't now how to explain but i have two table in my database.我现在不知道如何解释,但我的数据库中有两个表。

  • tab 1: service标签 1:服务
  • tab 2: department选项卡 2:部门

service table:服务表:

idService
serviceName
department_ID
is_deleted

department table:部门表:

departmentId
departmenetName
is_deleted

I want select all services with the departement name but with departement also if there is no service assigned to it.我想要 select 所有具有部门名称的服务,但如果没有分配给它的服务,也需要部门。 if there is no service assigned to a departement then the flelds will be shown but i must have null or equivalent in idService field.如果没有分配给部门的服务,则将显示字段,但我必须在 idService 字段中有 null 或等效项。 The result would be like this:结果将是这样的:

serviceID服务标识 serviceName服务名称 departmentId部门编号 departmenetName部门名称
1 1 IT 2 2 SI SI
2 2 Maintenance维护 6 6 Mechanical机械的
3 3 Maintenance维护 6 6 Mechanical机械的
4 4 Opt Manager选择经理 7 7 Finance金融
5 5 Instrument乐器 5 5 Electric电的
NULL NULL NULL NULL 1 1 Civil民事
8 8 Agro农业 NULL NULL NULL NULL
_________ _________ ___________ ___________ ____________ ____________ _______________ _______________

I have tried all kind of join options but I couldn't find the logic behind.我尝试了各种加入选项,但找不到背后的逻辑。 I use Mysql as DB Any idea please?我使用 Mysql 作为 DB 有什么想法吗? Thank you.谢谢你。

you could try using an union between the left joined tables whit and without service你可以尝试在左连接表之间使用联合,而没有服务

    select a.serviceID, a.serviceNam, b.departmentId, b.departmenetName
    from service a
    left join department b on a.department_ID = b.departmentId 
    UNION 
    select null, null, b.departmentId, b.departmenetName
    from department b 
    left join service a a.department_ID = b.departmentId  
    where a.serviceID is null  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM