0
我正在研究一個MySQL數據庫,我需要查詢數據庫並找出具有多個訂單的用戶。我嘗試過使用COUNT(),但我無法正確理解它。你能解釋一下正確的方法嗎?如何計算超過1個訂單的用戶?
這裏是我的表:
用戶
+-------------+----------+------------------+------------+ | userID | fName | email | phone | +-------------+----------+------------------+------------+ | adele012 | Adele | [email protected] || | ana022 | Anna | [email protected] | 0228374847 | | david2012 | David | [email protected] | 902849302 | | jefAlan | Jeffery | [email protected] | 0338473837 | | josquein | Joseph | [email protected],com | 0098374678 | | jweiz | John | [email protected] | 3294783784 | | jwick123 | John | [email protected] | 0998398390 | | kenwipp | Kenneth | [email protected] | 0112938394 | | mathCler | Maththew | [email protected] | 0238927483 | | natalij2012 | Natalie | [email protected] || +-------------+----------+------------------+------------+
訂單
+---------+------------+-------------+-------------+ | orderID | date | User_userID | orderStatus | +---------+------------+-------------+-------------+ | 1 | 2012-01-10 | david2012 | Delivered | | 2 | 2012-01-15 | jweiz | Delivered | | 3 | 2013-08-15 | david2012 | Delivered | | 4 | 2013-03-15 | natalij2012 | Delivered | | 5 | 2014-03-04 | josquein | Delivered | | 6 | 2014-01-15 | jweiz | Delivered | | 7 | 2014-02-15 | josquein | Delivered | | 8 | 2015-10-12 | jwick123 | Delivered | | 9 | 2015-02-20 | ana022 | Delivered | | 10 | 2015-11-20 | kenwipp | Processed | +---------+------------+-------------+-------------+
這是正確的目標。它也可以被寫爲'select_user_userID from orders group by user_userID having count(*)> 1'。另外,根據OP的數據集大小比較'where exists'與'where user_id in'的速度是有益的 – zedfoxus
我忘記在我的初始查詢中使用GROUP BY。 第一個工作正常。但是,當我試圖獲得更多的信息使用子查詢 它失敗,錯誤 錯誤1054(42S22):'IN/ALL/ANY子查詢中的未知列'user_ID' –
這對我有用 SELECT * FROM User WHERE userID IN ( SELECT User_userID as userID FROM Orders GROUP BY User_userID HAVING count(*)> 1 ); –