我有一个很大的mysql查询需要遍历4个表来获取我的应用程序的所有“项目”。每个项目可以有多个类别,每个用户最多可以有一个项目。项目和类别很简单:
SELECT Items.itemId, Items.name, Items.type, Categories.name AS category
FROM Items
LEFT JOIN ItemCategories ON Items.itemId = ItemCategories.itemId
LEFT JOIN Categories ON ItemCategories.categoryId = Categories.categoryId;
这会产生我想要的大部分数据。但是,我还需要知道每个项目是否归特定用户所有。所以我只是添加了另一个连接和一个布尔列:
SELECT Items.itemId, Items.name, Items.type, Categories.name AS category,
UserItems.userId = 7654321 AS userHas FROM Items
LEFT JOIN ItemCategories ON Items.itemId = ItemCategories.itemId
LEFT JOIN Categories ON ItemCategories.categoryId = Categories.categoryId
LEFT JOIN UserItems ON Items.itemId = UserItems.itemId;
这个问题是它会产生很多不必要的结果。例如,如果我有500个用户,每个用户有50个项目,则会有25,000行。由于数据库中只有大约100个项目,每个项目大约有3个类别,所以我只需要大约300行。基本上我不需要了解其他用户可能拥有的项目,只需要了解我感兴趣的特定用户。
我的下一步是尝试对行进行分组:
GROUP BY Items.itemId, Categories.name
但是,这并不能确保保留userHas列中我的用户数据。我试过SORT BY userHas DESC,但这似乎是在GROUP BY之后应用的。
我觉得解决方案可能涉及以下功能之一:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html 但我被困在什么或如何。我知道在一个查询中甚至可能无法实现。
这是一些输出(不使用GROUP BY):
+--------+--------+-----------+----------+---------+
| itemId | name | type | category | userHas |
+--------+--------+-----------+----------+---------+
| 1 | Llama | character | animal | NULL |
| 1 | Llama | character | nice | NULL |
| 2 | Slug | character | animal | 0 |
| 2 | Slug | character | animal | 1 |
| 2 | Slug | character | nasty | 0 |
| 2 | Slug | character | nasty | 1 |
| 3 | Sloth | character | animal | 1 |
| 3 | Sloth | character | animal | 0 |
| 4 | Banana | character | fruit | 0 |
| 4 | Banana | character | animal | 0 |
+--------+--------+-----------+----------+---------+
我想要每个项目ID,名称,键入所有类别以及用户是否有一个。与GROUP BY Items.itemId相同的数据集,Categories.name看起来像:
+--------+--------+-----------+----------+---------+
| itemId | name | type | category | userHas |
+--------+--------+-----------+----------+---------+
| 1 | Llama | character | animal | NULL |
| 1 | Llama | character | nice | NULL |
| 2 | Slug | character | animal | 0 |
| 2 | Slug | character | nasty | 0 |
| 3 | Sloth | character | animal | 1 |
| 4 | Banana | character | animal | 0 |
| 4 | Banana | character | fruit | 0 |
+--------+--------+-----------+----------+---------+
Slug的userHas = 1字段已在GROUP BY中丢失。我想保存它。
答案 0 :(得分:2)
<强>更新强>
这将选择所有项目并显示用户7654321
是否拥有它们。
SELECT Items.itemId, Items.name, Items.type, Categories.name AS category,
NOT(ISNULL(UserID)) AS userHas
FROM Items
LEFT JOIN
ItemCategories
ON Items.itemId = ItemCategories.itemId
LEFT JOIN
Categories
ON ItemCategories.categoryId = Categories.categoryId
LEFT JOIN
UserItems
ON UserItems.itemId = Items.itemID
AND UserItems.userId = 7654321
答案 1 :(得分:0)
您是否尝试将UserHas
列添加到GROUP BY
子句?