如何在MYSQL中从客户获取特定名称?

时间:2016-05-06 08:25:23

标签: mysql sql

我创建了以下表格:

create table customers
(
        ID             varchar(9),
        name           varchar(15),  

CONSTRAINT pk_id PRIMARY KEY (ID)
);


create table living_places
(
        code     varchar(7),
        ID      varchar(9),

CONSTRAINT pk_code PRIMARY KEY (code)
);

create table policies
(
        code_policy         varchar(7),
        code_living_place       varchar(7),

CONSTRAINT pk_code_policy PRIMARY KEY (code_policy)
);

create table accidents
(
        code_accident         varchar(7),
        code_policy       varchar(7),

CONSTRAINT pk_code_accident PRIMARY KEY (code_accident)
);

我插入了以下日期:

insert into customers(ID, name) 
values('fx1','Louis');
insert into customers(ID, name) 
values('fx2','Peter');
insert into customers(ID, name) 
values('fx3','Alice');

insert into living_places(code, ID) 
values('001','fx1');
insert into living_places(code, ID) 
values('002','fx2');
insert into living_places(code, ID) 
values('003','fx1');
insert into living_places(code, ID) 
values('004','fx3');

insert into policies(code_policy, code_living_place) 
values('p1','001');
insert into policies(code_policy, code_living_place) 
values('p2','002');
insert into policies(code_policy, code_living_place) 
values('p3','003');

insert into accidents(code_accident, code_policy) 
values('A1','p1');
insert into accidents(code_accident, code_policy) 
values('A2','p2');

问题是:如何选择在任何政策中没有发生事故的客户?

我的问题是当我试图使用“不在”时。 “路易斯”至少有一个政策在表“事故”中,查询显示我“路易斯”,不应该显示“路易”

我的查询:

create or replace view view as
select code from living_places v where code not in (
  select distinct a.code_living_place  from 
    policies as a inner join accidents as c 
    on a.code_policy = c.code_policy 
);

select name from customers where ID in (select ID from living_places where code in (select code from view where code in (select code_living_place from policies)));

MySQL回复我:

+-------+
| name  |
+-------+
| Louis |
+-------+

2 个答案:

答案 0 :(得分:1)

Select name FROM customers WHERE ID NOT IN (
    Select v.ID FROM
    accidents a, policies p, living_places v
    WHERE a.code_policy = p.code_policy
    AND p.code_living_place = v.code
)

答案 1 :(得分:1)

使用not in和inner join

select name from customers 
where customers.id not in (select living_places.id 
        from living_places
        inner join policies on policies.code_living_place = living_places.code
        inner join accidents on accidents.code_policy =  policies.code_policy);