mySQL左外部联接未选择可能的所有数据

我正在尝试同时匹配userIngredient.i_id和recipe_ingredient.i_id,并比较并比较配方_ingredient.i_id的所有值,我尝试查询的结果仅显示所有匹配的i_id,而没有不匹配的i_id,这是数据-

recipe_ingredients表:

+---------+------+
| post_id | i_id |
+---------+------+
| ifqnnv  | 1    |
+---------+------+
| ifqnnv  | 2    |
+---------+------+
| ifqnnv  | 3    |
+---------+------+
| ifqnnv  | 4    |
+---------+------+

userIngredient表:

+---------+------+
| user_id | i_id |
+---------+------+
| 4       | 1    |
+---------+------+
| 4       | 2    |
+---------+------+
| 4       | 3    |
+---------+------+

我尝试过的查询:

SELECT userIngredients.i_id,recipe_ingredients.i_id,recipe_ingredients.recipe_id,CASE
    WHEN userIngredients.i_id = recipe_ingredients.i_id THEN "true"
    WHEN userIngredients.i_id != recipe_ingredients.i_id THEN "false" 
    END as state
FROM userIngredients
LEFT OUTER JOIN recipe_ingredients
ON userIngredients.i_id = recipe_ingredients.i_id
WHERE userIngredients.uid = 4 AND recipe_ingredients.post_id = 'ifqnnv'

我得到的输出:

+------+------+-----------+-------+
| i_id | i_id | recipe_id | state |
+------+------+-----------+-------+
| 1    | 1    | ifqnnv    | true  |
+------+------+-----------+-------+
| 2    | 2    | ifqnnv    | true  |
+------+------+-----------+-------+
| 3    | 3    | ifqnnv    | true  |
+------+------+-----------+-------+

所需的输出:

+------+------+-----------+-------+
| i_id | i_id | recipe_id | state |
+------+------+-----------+-------+
| 1    | 1    | ifqnnv    | true  |
+------+------+-----------+-------+
| 2    | 2    | ifqnnv    | true  |
+------+------+-----------+-------+
| 3    | 3    | ifqnnv    | true  |
+------+------+-----------+-------+
| null | 4    | ifqnnv    | false |
+------+------+-----------+-------+
niuhenan 回答:mySQL左外部联接未选择可能的所有数据

将条件left join上的条件移到on的{​​{1}}一侧。否则,如果join不匹配,并且从结果集中删除相应的记录,则永远无法满足此条件。

left join

旁注:

  • 表示全表别名使查询更加简洁和易于理解;当查询涉及多个表时,请始终使用它们

  • SELECT i.i_id,r.i_id,r.recipe_id,CASE WHEN i.i_id = r.i_id THEN 'true' ELSE 'false' END as state FROM userIngredients u LEFT OUTER JOIN recipe_ingredients r ON i.i_id = r.i_id AND r.post_id = 'ifqnnv' WHERE i.uid = 4 表达式可以简化为case,因为两个要检查的条件在逻辑上都是相反的

  • 使用单引号而不是双引号来分隔字符串;这与SQL标准相对应,而某些RDBMS也使用双引号作为标识符

  • 使用驼峰大小写(WHEN ... ELSE ...)和下划线(userIngredient)混合表名容易出错;实际上,请使用下划线将表名和列名分开,因为某些RDBMS以区分大小写的方式管理表名,从而使骆驼的大小写毫无意义

,

使用left join时,order matters。要获得理想的结果,请在userIngredients上加入recipe_ingredients

本文链接:https://www.f2er.com/3163604.html

大家都在问