繁体   English   中英

MySQL - 正确地从两个表中获取用户及其订单数据

[英]MySQL - get users and their orders data from two tables correctly

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

USERS

用户身份

ownerid(用户所有者ID,与主用户一样)

公司

命令

ID

日期(订单下达日期)

用户身份

我需要让所有用户与一个所有者相关(ownerid,例如52,例如),他们在选定的时间段内下订单,作为带有一些字段的数组(参见查询)。 不幸的是,我的请求给出了一个(不是数组)而不是当前结果(有时甚至在所有字段中都为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

看起来我忘了在最后添加:

GROUP BY ei_users.userid

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM