Sql左侧使用filter连接两列

时间:2013-09-24 16:12:01

标签: mysql 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

我可以添加一个标志,以便我可以确定食物对是否已连接或是否为空?我不想内心加入,因为我需要计算每人的食物/食物总量,以及每人的食物/配对数量。我试过了:

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

但它不起作用。基本上我只需要在没有应用连接时标记,但是我遇到了麻烦。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

使用MySQL,表达式将返回一个布尔值true / false 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

答案 2 :(得分: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

答案 3 :(得分:0)

当表达式为NULL时返回1,否则返回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