简体   繁体   中英

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

I have users and orders tables with this structure (simplified for question):

USERS

userid

ownerid (user owner id, like main user)

company

ORDERS

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). Unfortunately my request give ONE (not array) and not current result (sometimes even null in all fields). 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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