SQL查询比较3个表并得到答案

时间:2013-10-24 12:55:42

标签: mysql sql

请帮我一些sql查询..

我有3张桌子:

CREATE TABLE cars (
    id integer not null primary key,  -- id of car
    name text not null, -- car name
)

- 意外

CREATE TABLE accidents (
    id integer not null primary key, -- id of accident
    place text not null, -- place of accident
    a_date date not null -- date of accident
)

- 意外结果

CREATE TABLE outcomes (
    car_id integer not null, -- id of car
    accident_id integer not null, -- id of accident
    result smallint not null, -- result: 0 - fine, 1 - scratched, 2 - crashed
    CONSTRAINT outcomes_pkey PRIMARY KEY (car_id, accident_id)
)

我需要一个sql查询来获取曾被划伤过的汽车,而不是再次发生事故,当然坠毁的汽车不会发生其他事故。

1 个答案:

答案 0 :(得分:0)

试试这个

select c.id, c.name, count(distinct o.results) cnt
from cars c
inner join outcomes o on c.id = o.car_id
where o.results in (1,2)
group by c.id, c.name
having count(distinct o.results) > 1;