简体   繁体   English

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

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

I have users and orders tables with this structure (simplified for question): 我有这种结构的用户和订单表(简化问题):

USERS USERS

userid 用户身份

ownerid (user owner id, like main user) ownerid(用户所有者ID,与主用户一样)

company 公司

ORDERS 命令

id ID

date (order placed date) 日期(订单下达日期)

user_id 用户身份

total

I need to get all users related to one owner (ownerid, let's say 52 for example) who placed orders within selected period, as array with some fields (see in query). 我需要让所有用户与一个所有者相关(ownerid,例如52,例如),他们在选定的时间段内下订单,作为带有一些字段的数组(参见查询)。 Unfortunately my request give ONE (not array) and not current result (sometimes even null in all fields). 不幸的是,我的请求给出了一个(不是数组)而不是当前结果(有时甚至在所有字段中都为null)。 This is my request: 这是我的要求:

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"

Please let me know what is wrong with my request and why I does not get array with results? 请告诉我我的请求有什么问题以及为什么我没有获得结果数组?

I found my mistake, I forgot to add GROUP BY ei_users.userid at the end: 我发现了我的错误,我忘了在最后添加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