我在MySQL中设置了以下4个表。我希望能够使用连接从所有数据中输出数据的某些数据,但我似乎无法使其工作。
TABLE books
---------------------------
| id | name |
---------------------------
| 1 | War of the Worlds |
| 2 | The Treasure Island |
| 3 | The Hobbit |
| 4 | Friend or Foe |
---------------------------
TABLE users
--------------
| id | name |
--------------
| 1 | Alfie |
| 2 | Ben |
| 3 | Charlie |
| 4 | Doug |
--------------
TABLE library
-------------------
| user_id | book_id |
-------------------
| 1 | 1 |
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 2 | 2 |
| 4 | 4 |
-------------------
TABLE reviews
------------------
| book_id | rating |
------------------
| 1 | 4 |
| 1 | 3 |
| 1 | 4 |
| 3 | 5 |
| 4 | 1 |
| 4 | 3 |
| 4 | 1 |
------------------
我尝试使用以下MySQL查询:
SELECT
library.user_id,
users.name,
library.book_id,
books.name,
COUNT(reviews.book_id)
FROM library
JOIN users
ON users.id = library.user_id
JOIN books
ON books.id = library.book_id
LEFT JOIN reviews
ON reviews.book_id = books.id
WHERE library.user_id = 1;
我希望输出符合以下内容:
------------------------------------------------------------
| user_id | users.name | book_id | books.name | COUNT |
------------------------------------------------------------
| 1 | Alfie | 1 | War of the Worlds | 3 |
| 1 | Alfie | 3 | The Hobbit | 1 |
| 1 | Alfie | 4 | Friend or Foe | 3 |
------------------------------------------------------------
但我得到的所有问题都是:
------------------------------------------------------------
| user_id | users.name | book_id | books.name | COUNT |
------------------------------------------------------------
| 1 | Alfie | 1 | War of the Worlds | 7 |
------------------------------------------------------------
我很抱歉,如果这听起来真的很愚蠢,因为我可能只是愚蠢但我现在已经玩了很多年了,我无法理解一件事,所以任何帮助都会非常感谢。非常感谢你的时间。
P.S。对于糟糕的格式化道歉,我试图让它变得尽可能简单:)
答案 0 :(得分:0)
由于您正在使用计数,请尝试根据user_id,name,book_id,book_name对查询进行分组
{{1}}