mySQL左外部联接未选择可能的所有数据
我正在尝试匹配UserComponent.i_id和recipe_Component.i_id,并匹配和比较recipe_Component.i_id的所有值,我尝试的查询只显示所有匹配的i_id,而不显示不匹配的i_id,数据如下- 配方和配料表:mySQL左外部联接未选择可能的所有数据,mysql,database,phpmyadmin,Mysql,Database,Phpmyadmin,我正在尝试匹配UserComponent.i_id和recipe_Component.i_id,并匹配和比较recipe_Component.i_id的所有值,我尝试的查询只显示所有匹配的i_id,而不显示不匹配的i_id,数据如下- 配方和配料表: +---------+------+ | post_id | i_id | +---------+------+ | ifqnnv | 1 | +---------+------+ | ifqnnv | 2 | +---------
+---------+------+
| post_id | i_id |
+---------+------+
| ifqnnv | 1 |
+---------+------+
| ifqnnv | 2 |
+---------+------+
| ifqnnv | 3 |
+---------+------+
| ifqnnv | 4 |
+---------+------+
用户成分表:
+---------+------+
| 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 |
+------+------+-----------+-------+
将
left join
ed表中的条件移动到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
旁注:
- 有意义的是,完整的表别名使查询更简洁、更容易理解;当查询涉及多个表时,始终使用它们
- 当。。。否则…
,因为正在检查的两个条件在逻辑上是相反的
使用单引号而不是双引号来分隔字符串;这与SQL标准相对应,同时一些RDBMS使用双引号作为标识符
将表格名称与驼峰大小写(usercomponent
)和下划线分隔(recipe\u components
)混合使用容易出错;事实上,使用下划线分隔的表名和列名,因为有些RDBMS以不区分大小写的方式管理表名,这使得camel大小写毫无意义
当使用左连接时。要获得您想要的结果,请在recipe\u components