2016-05-06 16 views
1

私は、次の表を作成します。MYSQLの顧客から特定の名前を取得する方法は?

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'); 

質問がある:彼らのポリシーのいずれかで持っていた事故を持っていけない顧客を選択する方法?

私の問題は、「not in」を使用しようとしていたときです。表中の「ルイ」は、少なくとも1つのポリシー「事故」を有する、クエリが「ルイ」私を見ると「ルイ」

私のクエリを示してはならない。

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 | 
+-------+ 
+0

'NOT Iに参加サブクエリがnullを返す場合、Nは多くのユーザーを驚かせるかもしれません。私のヒントは、 'NOT EXISTS'を使うか、サブクエリがヌルを返さないようにすることです。 – jarlh

+0

なぜそれらの奇妙なID列のデータ型ですか?整数に何が問題なのですか? – jarlh

答えて

1

使用しないで、内側

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); 
+0

完璧に動作します。ありがとうございます :) – Python241820

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 
) 
+0

それは完璧に動作します。ありがとうございます:) – Python241820

関連する問題