mysql嵌套查询如何解决?

时间:2019-01-20 17:05:14

标签: mysql sql

这是我的查询和输出。现在,我尝试用

来计算唯一item_id和名称的总和
SELECT name, SUM(item_id) 
FROM (SELECT *
      FROM items U
      JOIN users_items UI ON UI.item_id = U.id)

但显示错误

enter image description here

4 个答案:

答案 0 :(得分:0)

您在下面找到了什么

 select name, sum(item_id) FROM items U
 JOIN users_items UI ON UI.item_id = U.id
 group  by name

答案 1 :(得分:0)

由于需要唯一的item_id的总和,因此需要将DISTINCTSUM一起使用:

 SELECT 
   name, 
   SUM(DISTINCT item_id) 
 FROM items U
 JOIN users_items UI 
   ON UI.item_id = U.id

答案 2 :(得分:0)

因为您需要为子查询使用别名,并按group by name的形式按表达式分组

SELECT q.name, SUM(q.item_id) 
FROM (SELECT *
      FROM items U
      JOIN users_items UI ON UI.item_id = U.id) q
GROUP BY q.name

答案 3 :(得分:0)

与每个项目的唯一SUM相比,每个用户唯一的COUNT个项目更有意义。

SELECT usr.name as user_name, COUNT(DISTINCT uitem.item_id) AS TotalUniqueItems
FROM users AS usr
JOIN users_items AS uitem ON uitem.user_id = usr.id
GROUP BY usr.id, usr.name
ORDER BY usr.name

反之亦然,每个项目的唯一用户数

SELECT item.name as item_name, COUNT(DISTINCT uitem.user_id) AS TotalUniqueUsers
FROM items AS item
JOIN users_items AS uitem ON uitem.item_id = item.id
GROUP BY item.id, item.name
ORDER BY item.name