简体   繁体   中英

Sql left join across two columns with filter

UPDATE: This is resolved, I was making a syntax error.


Can I join and filter across two columns in a left join? For example:

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

Then using 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

Can I add a flag so that I can determine whether or not the food pair is in joined or if it's NULL? I don't want to inner join, because I need to count total food/sides per person, and also matching food/side pairs per person. I tried:

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

But it's not working. Basically I just need to flag when the join isn't applied but I'm having trouble.

I think what you want is this:

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

With MySQL an expression will return a boolean true/false 1/0, works as a shorthand CASE statement when looking for boolean output.

This will work to flag the non-matching with 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

Demo: SQL Fiddle

Or this to flag the non-matching as 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

Demo: SQL Fiddle

Try to flag null value before join

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

It returns 1 when the expression is NULL otherwise it returns 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM