我有3個表格。第一個有我想要的記錄。另外兩個類別可以應用於第一個表格。如果在描述中找到table3的查找值,我想返回該類別。否則,返回table2中的類別。我認爲我的邏輯是正確的,但結果正在倍增。我怎樣才能將結果限制爲我想要的table1記錄,但應用正確的類別?PostgreSQL 3表連接乘法
這是我的查詢與示例架構。它應該只在表1與哪個類別是正確的返回第6行,但它返回10 http://sqlfiddle.com/#!15/fc6fa/49/0
SELECT table1.product_code, table1.date_signed, table1.description,
CASE
WHEN lower(table1.description) LIKE ('%' || lower(table3.lookup_value) || '%')
THEN table3.category
ELSE table2.category
END
FROM table1
LEFT JOIN table2 ON table2.psc_code = table1.product_code
LEFT JOIN table3 ON table3.psc_code = table1.product_code
WHERE date_signed = '2017-02-01';
create table table1 (
product_code int,
date_signed timestamp,
description varchar(20)
);
insert into table1
(product_code, date_signed, description)
values
(1, '2017-02-01', 'i have a RED car'),
(2, '2017-02-01', 'i have a blue boat'),
(3, '2017-02-01', 'i have a dark cat'),
(1, '2017-02-01', 'i have a green truck'),
(2, '2017-02-01', 'i have a blue rug'),
(3, '2017-02-01', 'i have a dark dog'),
(1, '2017-02-02', 'i REd NO SHOW'),
(2, '2017-02-02', 'i blue NO SHOW'),
(3, '2017-02-02', 'i dark NO SHOW');
create table table2 (
psc_code int,
category varchar(20)
);
insert into table2
(psc_code, category)
values
(1, 'vehicle'),
(2, 'vehicle');
create table table3 (
psc_code int,
lookup_value varchar(20),
category varchar(20)
);
insert into table3
(psc_code, lookup_value, category)
values
(1, 'fox', 'animal'),
(1, 'red', 'color'),
(1, 'box', 'shipping'),
(2, 'cat', 'animal');
我看到,得到的結果適量,而是通過我的計算,PRODUCT_CODE 3不應該有一個類別,對不對?爲什麼它會在前三次獲得動物? – user2634997
,因爲我失去了where子句,讓我編輯 – McNets
謝謝,就是這樣! – user2634997