2013-09-24 58 views
0

更新:這已解決,我正在發出語法錯誤。Sql用兩個列左加入過濾器


我可以連接並過濾左連接中的兩列嗎?例如:

tbl_people 
id food  side  value 
a  pizza fries 10 
b  pizza shake  2 
c  burger fries 3 

tbl_sides 
food  side 
pizza fries 
burger fries 

然後利用SQL:

SELECT 
    id, food, side, value 
FROM 
    tbl_people AS people 
LEFT JOIN 
    tbl_sides AS sides ON sides.food = people.food 
    AND sides.side = people.side 

我可以添加一個標誌,以便我能確定的食品對是否是在加入或如果它是NULL?我不想內部加入,因爲我需要計算每個人的總食量/人數,並且還要匹配每個人的食物/人對。我試過:

SELECT 
    id, food, side, value, 
    CASE WHEN 
    side.side IS NOT NULL 
    AND side.food IS NOT NULL 
    THEN 1 
    ELSE 0 
    END AS match_flag 
FROM 
    tbl_people AS people 
LEFT JOIN 
    tbl_sides AS sides ON sides.food = people.food 
    AND sides.side = people.side 

但它不工作。基本上我只需要標記何時未加入連接但我遇到問題。

回答

1

我想你想要的是這樣的:

SELECT 
    id, food, side, value, 
    CASE WHEN 
    side.side = people.side 
    THEN 1 
    ELSE 0 
    END AS match_flag 
FROM 
    tbl_people AS people 
LEFT JOIN 
    tbl_sides AS sides ON people.food = sides.food 
+0

哦,你說的沒錯,我是過於複雜,我很抱歉。 –

1

隨着MySQL的表達式,將返回一個true /假1/0,尋找布爾輸出時,作爲速記CASE聲明。

這將致力於標誌不匹配,用1:

SELECT 
    people.id, people.food, people.side, people.value 
    ,sides.food IS NULL AS match_flag 
FROM 
    tbl_people AS people 
LEFT JOIN tbl_sides AS sides 
    ON sides.food = people.food 
    AND sides.side = people.side 

演示:SQL Fiddle

或者這標誌不匹配的爲0:

SELECT 
    people.id, people.food, people.side, people.value 
    ,COALESCE(sides.food = people.food,0) AS match_flag 
FROM 
    tbl_people AS people 
LEFT JOIN tbl_sides AS sides 
    ON sides.food = people.food 
    AND sides.side = people.side 

演示: SQL Fiddle

0

嘗試在連接前標記空值

SELECT 
    people.id, people.food, people.side, people.value, nvl(sides.side, 'NOT JOINED') 
FROM 
    tbl_people AS people 
LEFT JOIN 
    (select food, nvl(side, 'SOME NULL') as side from tbl_sides) AS sides 
ON sides.food = people.food 
AND sides.side = people.side 
0

它返回1時,表達式爲NULL,否則返回0

http://sqlfiddle.com/#!2/cadbdd/15/0

SELECT *, ISNULL(sides.food) AS match_flag 
FROM 
    tbl_people AS people 
LEFT JOIN 
    tbl_sides AS sides ON sides.food = people.food 
    AND sides.side = people.side