如何从子查询SQLite接收两个值

时间:2013-06-24 11:56:10

标签: sql database sqlite

我是SQLite的自学者和新手。我有三个表(person,pet,person_pet),而.schema是:

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*/
    );

我的任务是编写一个查询,可以找到2004年后购买的宠物及其所有者的所有名称。关键是将基于purchase_on列的person_pet映射到宠物和父母。 我尝试做一个子查询,返回两个值,但它不起作用。 (有些人会说:“很明显”。)我的问题是:如果我不能从子查询返回两个值,我怎么能完成这个任务呢?

我尝试了这个子查询:

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:对不起,如果我的问题有点长。

3 个答案:

答案 0 :(得分:1)

您不需要子查询。你需要加入:

SELECT p.id, p.first_name, p.last_name, p2.id as pet_id, p2.name as pet_name
FROM person as p
INNER JOIN person_pet as pp on pp.person_id = p.id
INNER JOIN pet as p2 on p2.id = pp.pet_id
WHERE 
p2.purchased_on > '2004/01/01 0:0:0 AM'

答案 1 :(得分:0)

SELECT a.id, a.first_name, a.last_name, c.id pet_id, c.name pet_name
FROM person a, person_pet b, pet c 
WHERE b.person_id =a.id
and  c.id = b.pet_id
and c.purchased_on > '2004/01/01'

请参阅DEMO HERE

答案 2 :(得分:0)

如果你真的想用子查询来做这件事,你可以这样做:

SELECT (SELECT first_name
        FROM person
        WHERE id = person_pet.person_id),
       (SELECT name
        FROM pet
        WHERE id = person_pet.pet_id)
FROM person_pet
WHERE pet_id IN (SELECT id
                 FROM pet
                 WHERE purchased_on >= '2004');

但加入可能会更有效率。