Reputation: 6668
I have two tables. I have a simple inner join query where fields are selected from two tables, Deals and Deals_Country.
Both tables share a field called Id. This is a primary key in Deals & a foreign key in Deals_Country. So an id is always unique in Deals but not always unique in Deals_Country.
I want to add a further condition to my simple inner join query. I want to return only records where there is more than one id in MA_DEALS_COUNTRY. Please see an example below.
select DEALS.id, DEALS.field_b, DEALS_COUNTRY.field_c DEALS_COUNTRY.field_d,
from DEALS
inner join DEALS_COUNTRY
on DEALS.id = DEALS_COUNTRY.id
where
(
select id
from DEALS_COUNTRY
group by id
having count(id) > 1
)
order by id
DEALS
id
AA11
AB34
AN21
BN44
DEALS_COUNTRY
id some_code
AA11 4506
AB34 5052
AB34 6161
AB34 0124
AN21 6322
AN21 9548
BN44 0012
Result
Deal.id Deal_Country.some_code
AB34 5052
AB34 6161
AB34 0124
AN21 6322
AN21 9548
Upvotes: 0
Views: 725
Reputation: 35573
an alternative approach is to use count() over()
SELECT
id
, field_b
, field_c
, field_d
FROM (
SELECT
DEALS.id
, DEALS.field_b
, DEALS_COUNTRY.field_c
, DEALS_COUNTRY.field_d
, COUNT(*) OVER (PARTITION BY DEALS_COUNTRY.id) AS cnt
FROM DEALS
INNER JOIN DEALS_COUNTRY
ON DEALS.id = DEALS_COUNTRY.id
) AS sq
WHERE cnt > 1
Upvotes: 1
Reputation: 24763
select DEALS.id, DEALS.field_b, DEALS_COUNTRY.field_c DEALS_COUNTRY.field_d,
from DEALS
inner join DEALS_COUNTRY
on DEALS.id = DEALS_COUNTRY.id
where exists
(
select x.id
from DEALS_COUNTRY x
where x.id = DEALS.id
group by x.id
having count(x.id) > 1
)
order by deal_id
Upvotes: 1