简体   繁体   English

如何将这两个查询结合起来,使结果在一个表中?

[英]How can I combine these two queries such that the results are in one table?

First query:第一个查询:

SELECT integration_department_map.foreign_department_key AS 'Department Code', department.department_name AS 'Department Name'
FROM integration_department_map
JOIN department ON department.department_id = integration_department_map.department_id
WHERE integration_department_map.client_id = '10134';

Second query:第二个查询:

SELECT integration_department_map.foreign_department_key AS 'Department Code', location.location_name AS 'Location Name'
FROM integration_department_map
JOIN location ON location.location_id = integration_department_map.location_id
WHERE integration_department_map.client_id = '10134';

They both return the results needed separately, but I want to know if there is a way they could be written as one query?它们都分别返回所需的结果,但我想知道是否有一种方法可以将它们写为一个查询?

As suggested by honeybadger in the comments .正如蜜獾评论中所建议的那样。 Just add a join to location table like:只需向位置表添加一个join ,例如:

SELECT 
    i.foreign_department_key AS `Department Code`, 
    d.department_name AS `Department Name`, 
    l.location_name AS `Location Name`
FROM integration_department_map i
JOIN department d
ON d.department_id = i.department_id
JOIN location l
ON l.location_id = i.location_id
WHERE i.client_id = 10134

And remove quotes around id if it's an int as it should be.如果它应该是一个int ,则删除id周围的引号。

Perhaps what you are looking for is a LEFT JOIN and not a JOIN (inner join).也许您正在寻找的是 LEFT JOIN 而不是 JOIN(内连接)。 How many lines in the original integration_department_map satisfy the WHERE clause, and are they the same lines?原始 integration_department_map 中有多少行满足 WHERE 子句,它们是同一行吗?

maybe this will do the trick -也许这会奏效-

SELECT 
    i.id,
    i.foreign_department_key AS `Department Code`, 
    d.department_name AS `Department Name`, 
    l.location_name AS `Location Name`
FROM integration_department_map i
LEFT JOIN department d ON d.department_id = i.department_id
LEFT JOIN location l   ON l.location_id = i.location_id
WHERE i.client_id = 10134

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

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