I have a table schema as
create table Location(
id int primary key,
city varchar(255),
state varchar(100),
country varchar(255)
);
create table Person(
id int primary key,
name varchar(100)
);
create table Photographer(
id int primary key references Person(id) on update cascade on delete cascade,
livesIn int not null references Location(id) on update cascade on delete no action
);
create table Specialty(
photographer int references Photographer(id) on update cascade on delete cascade,
type enum('portrait','landscape','sport'),
primary key(photographer, type)
);
create table Photo(
id int primary key,
takenAt timestamp not null,
takenBy int references Photographer(id) on update cascade on delete no action,
photographedAt int references Location(id) on update cascade on delete no action
);
create table Appearance(
shows int references Person(id) on update cascade on delete cascade,
isShownIn int references Photo(id) on update cascade on delete cascade,
primary key(shows, isShownIn)
);
I am stuck at two queries :
1) The photos such that the photo only shows photographers that live in the same location. List each photo once. That is, photos must have persons that are photographers, and they all need to live in the same place.
2) The locations that have the property that every photo in the location was taken by a photographer who is not shown in any photo in Massachusetts? For each location show only the city, and show each location only once.
My tries :
1)
SELECT ph.id, ph.takenAt, ph.takenBy, ph.photographedAt FROM
(SELECT * FROM Photo p, Appearance ap WHERE p.id = ap.isShownIn
HAVING ap.shows IN (SELECT person.id FROM Person,Photographer WHERE person.id
photographer.id)) ph
WHERE ph.photographedAt = (SELECT location.id FROM location WHERE location.id =
(SELECT livesIn FROM Photographer WHERE id = ph.takenBy))
2)
select distinct city from location where location.id in (
select photographedAt from photo, (select * from appearance where appearance.shows in
(select photographer.id from photographer)) ph
where photo.id = ph.isShownIn )
and location.state <> 'Massachusetts'
Can anyone help in creating these queries ??
Your queries are both of the “list individual items that have properties X and Y, where X and Y are in different tables” variety.
These types of questions are commonly solved using correlated sub-queries with
EXISTSandNOT EXISTS.Using
EXISTStakes care of the “show each item only once” part. Otherwise you would need to use grouping in conjunction with complex joins, and this can get messy very quickly.Question 1 requires:
Note that this definition doesn’t say “do not show photos if they contain other people, too”. If that’s what you really meant, it’s upon you to draw conclusions from the SQL below and to write better definitions next time. 😉
The second question reads
The according SQL would look like: