首页 > 解决方案 > MySQL - 从两个表中正确获取用户及其订单数据

问题描述

我有具有这种结构的用户和订单表(为问题而简化):

用户

用户身份

ownerid(用户所有者 id,如主用户)

公司

订单

ID

日期(下单日期)

用户身份

全部的

我需要获取与在选定期间下订单的一个所有者(例如,ownerid,例如 52)相关的所有用户,作为带有一些字段的数组(参见查询)。不幸的是,我的请求给出了 ONE(不是数组)而不是当前结果(有时甚至在所有字段中都为 null)。这是我的要求:

SELECT
  ei_users.userid as id,
  ei_users.company as company,
  ei_users.city as city,
  ei_users.user_type as user_type,
  ei_users.registered as registered,
  count(ei_orders.id) AS orders,
  sum(ei_orders.total) AS revenue
FROM
 ei_orders,
 ei_users
WHERE
 ei_users.userid = ei_orders.user_id 
 && ei_users.ownerid = 52 
 && DATE_FORMAT(ei_orders.date, "%b") = "Apr" 
 && DATE_FORMAT(ei_orders.date, "%Y") = "2019"

请让我知道我的请求有什么问题以及为什么我没有得到结果数组?

我发现我的错误,我忘了在最后添加GROUP BY ei_users.userid

SELECT
  ei_users.userid as id,
  ei_users.company as company,
  ei_users.city as city,
  ei_users.user_type as user_type,
  ei_users.registered as registered,
  count(ei_orders.id) AS orders,
  sum(ei_orders.total) AS revenue
FROM
 ei_orders,
 ei_users
WHERE
 ei_users.userid = ei_orders.user_id 
 && ei_users.ownerid = 52 
 && DATE_FORMAT(ei_orders.date, "%b") = "Apr" 
 && DATE_FORMAT(ei_orders.date, "%Y") = "2019"
GROUP BY ei_users.userid

标签: mysql

解决方案


最后好像忘记加了:

GROUP BY ei_users.userid

推荐阅读