【发布时间】:2014-08-17 16:11:45
【问题描述】:
所以我有 6 张桌子,每张桌子都有 2 列。 3 个有我正在使用的数据,另外 3 个只是指定它们之间的关系。
所以用这个示例数据:
central_item
id name
-----------------
1 Chicken
2 Shrimp
cooking_method
id name
-----------------
1 Bake
2 Fry
style
id name
-----------------
1 Casserole
2 Pie
central_item_cooking_method
central_item cooking_method
------------------------------
1 1
1 2
2 1
2 2
central_item_style
central_item style
------------------------------
1 1
1 2
2 1
cooking_method_style
cooking_method style
------------------------------
1 1
2 2
我正在努力解决这个问题:
central_item_name style_name cooking_method_name
----------------------------------------------------
Chicken null Bake
Chicken null Fry
Chicken Casserole null
Chicken Casserole Bake
Chicken Pie null
Chicken Pie Bake
Shrimp null Bake
Shrimp null Fry
Shrimp Casserole null
Shrimp Casserole Bake
这是我一直在尝试的查询。 cmets 解释了每个部分应该做什么。当我运行它时,查询会丢失很多我希望看到只有 1 列为空的结果。
SELECT
#name these something better so they don't all get returned as just 'name'
central_item.name as `central_item_name`, style.name as `style_name`, cooking_method.name as `cooking_method_name`
#we need a central item no matter what so start here
FROM central_item
#get styles for items (optional)
LEFT JOIN central_item_style ON central_item_style.style = central_item.id OR central_item_style.style IS NULL
#get names for any matching styles
LEFT JOIN style ON style.id = central_item_style.style OR style.id IS NULL
#get cooking methods for items (optional)
LEFT JOIN central_item_cooking_method ON central_item_cooking_method.central_item = central_item.id OR central_item_cooking_method.central_item IS NULL
#get names for cooking methods
LEFT JOIN cooking_method ON cooking_method.id = central_item_cooking_method.cooking_method OR cooking_method.id IS NULL
#for the matching item cooking methods check which styles also match the cooking method. For item styles check for matching cooking methods.
LEFT JOIN cooking_method_style ON cooking_method_style.style = central_item_style.style OR cooking_method_style.cooking_method = central_item_cooking_method.cooking_method
WHERE
#make sure we have at least one of these
(style.id IS NOT NULL OR cooking_method.id IS NOT NULL) AND
#cooking method or style can be null but we have both they need to be compatible with each other
(cooking_method.id IS NULL OR central_item_style.style = cooking_method_style.style) AND
(style.id IS NULL OR central_item_cooking_method.cooking_method = cooking_method_style.cooking_method)
#Remove duplicates
GROUP BY central_item.name, style.name, cooking_method.name
ORDER BY central_item.name, style.name, cooking_method.name
【问题讨论】:
-
这是一个垃圾例子。谁炸意大利面?
-
那里。我把它改成了虾。其余的仍然有意义。
-
好。一个项目有点像一种成分,不是吗?
-
您确定这是正确的结果集吗?
-
查看我的答案。这是正确的结果集。例如,您可以吃烤鸡。或者烤鸡砂锅。它们是 2 个不同的结果。
标签: mysql database join left-join