Click here to Skip to main content
16,004,602 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I hay this table Day
DayId   Name
---   ----
1      sun
2      mon
3      tue
4      wed

And this table Place
PlaceId  Loc  DayId
1      1     1
1      1     2
1      2     1
2      1     3
3      1     2
3      1     4

i want to to return the days that are not used for each (PlaceId and LocId) so the result should be as follows
PlaceId  Loc  DayId
1      1     3
1      1     4
1      2     2
1      2     3
1      2     4
2      1     1
2      1     2
2      1     4
3      1     1
3      1     3


What I have tried:

I don't want to use distinct but i don't know how to do it without getting duplicated records

select distinct Place.PlaceId, Place.Loc, Day.DayId
from Place
cross join Day
left join Place AS X
on Place.PlaceId = X.PlaceId
and Place.Loc = X.Loc
and Day.DayId = X.DayId
where x.DayId is null
Posted
Comments
carloscs 20-Apr-20 15:01pm    
With this schema you can't do it without using distinct or group by. [If you had a third PlaceLoc table with unique key columns (PlaceId, Loc) having all the place_locs you could do it].

However a slightly clear and more effective query is this one:

select p.PlaceId, p.Loc, d.DayId
from Place p, Day d
where not exists (select 1 from Place p2 where p2.PlaceId = p.PlaceId and p2.Loc = p.Loc and p2.DayId = d.DayId)
group by p.PlaceId, p.Loc, d.DayId

- it clearly tells what you wand to do - the other query is a bit obfuscated.
- the not exists correlated subquery should be a bit more optimized that the left join [allthough this can vary with differnte databases depending on the optimizer]

- note that the group by has the same effect as using distinct on the select part [I'm old school and prefer group by's :)]

Edit: query not tested, just a quick example
Member 14800672 20-Apr-20 16:26pm    
I will try ur query now(what does select 1 mean, 1 refers to what?) I do have a table called PlaceLoc how can i use it in my query to get the correct result without distinct?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900