簡體   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