私は、次の表を作成します。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 |
+-------+
'NOT Iに参加サブクエリがnullを返す場合、Nは多くのユーザーを驚かせるかもしれません。私のヒントは、 'NOT EXISTS'を使うか、サブクエリがヌルを返さないようにすることです。 – jarlh
なぜそれらの奇妙なID列のデータ型ですか?整数に何が問題なのですか? – jarlh