合并两个内部联接?
Combine two inner joins?
我有以下表格:
dealer
id (PK)
car
- id (PK)
- dealer_id (FK)
notes
- car_id (FK)
- dealer_id (FK)
- user_id (FK)
- is_active Bool
我希望能够 select 所有我有活跃票据的经销商。 当前型号不存储dealer_id在笔记上car_id 一次记笔记。这是一个非此即彼.
我可以单独查询:
select *
from dealer
inner join notes n on dealer.id = n.dealer_id and n.user_id=${userId} and n.is_active=true
和:
select *
from dealer
inner join car c on dealer.id = c.dealer_id
inner join notes n on c.id = n.car_id and n.user_id=${userId} and n.is_active=true
我试图在查询中简单地组合两个内部联接,但随后:
inner join car c on dealer.id = c.dealer_id
会筛选出第一个查询会给我什么,所以我不会得到我应该得到的所有经销商。
如何编写一个查询来提供我拥有有效备注的所有经销商?
我不想在结果中出现重复的经销商。
你快到了。你要的叫UNION:
SELECT n.*
FROM
notes AS n
INNER JOIN dealer AS d ON d.id = n.dealer_id
UNION
SELECT n.*
FROM
notes AS n
INNER JOIN car AS c ON c.id = n.car_id
INNER JOIN dealer AS d ON d.id = c.dealer_id
我有以下表格:
dealer
id (PK)
car
- id (PK)
- dealer_id (FK)
notes
- car_id (FK)
- dealer_id (FK)
- user_id (FK)
- is_active Bool
我希望能够 select 所有我有活跃票据的经销商。 当前型号不存储dealer_id在笔记上car_id 一次记笔记。这是一个非此即彼.
我可以单独查询:
select *
from dealer
inner join notes n on dealer.id = n.dealer_id and n.user_id=${userId} and n.is_active=true
和:
select *
from dealer
inner join car c on dealer.id = c.dealer_id
inner join notes n on c.id = n.car_id and n.user_id=${userId} and n.is_active=true
我试图在查询中简单地组合两个内部联接,但随后:
inner join car c on dealer.id = c.dealer_id
会筛选出第一个查询会给我什么,所以我不会得到我应该得到的所有经销商。
如何编写一个查询来提供我拥有有效备注的所有经销商? 我不想在结果中出现重复的经销商。
你快到了。你要的叫UNION:
SELECT n.*
FROM
notes AS n
INNER JOIN dealer AS d ON d.id = n.dealer_id
UNION
SELECT n.*
FROM
notes AS n
INNER JOIN car AS c ON c.id = n.car_id
INNER JOIN dealer AS d ON d.id = c.dealer_id