I'm a self-learning and newbie in SQLite. I have three tables (person, pet, person_pet) and the .schema is:
CREATE TABLE person (
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
age INTEGER,
dead INTEGER,
phone_number INTEGER,
salary FLOAT,
dob DATETIME
);
CREATE TABLE person_pet (
person_id INTEGER,
pet_id INTEGER,
);
CREATE TABLE pet (
id INTEGER PRIMARY KEY,
name TEXT,
breed TEXT,
age INTEGER,
dob DATETIME,
purchased_on DATETIME,
parent INTEGER /*Contains the ID of the pet's parent*/
);
My task is writing a query that can find all the names of pets and their owners bought after 2004. Key to this is to map the person_pet based on the purchased_on column to the pet and parent. I tried doing a subquery that returns two values but it doesn't work. (Some of you would say: "Obviously".) My question is: if I can't return two values from a subquery how can I achieve this task?
I tried this subquery:
SELECT first_name, name FROM person, pet WHERE person.id pet.id IN(
SELECT person_id FROM person_pet WHERE pet_id IN (
SELECT id FROM pet WHERE purchased_on IN (
SELECT pet.purchased_on
FROM pet, person_pet, person
WHERE person.id = person_pet.person_id AND
pet.id = person_pet.pet_id AND
pet.purchased_on > '2004/01/01 0:0:0 AM'
)
)
SELECT pet_id FROM person_pet WHERE id IN (
SELECT id FROM pet WHERE purchased_on IN (
SELECT pet.purchased_on
FROM pet, person_pet, person
WHERE person.id = person_pet.person_id AND
pet.id = person_pet.pet_id AND
pet.purchased_on > '2004/01/01 0:0:0 AM'
)
)
);
PS: Sorry if my question is a bit long.