2016-05-06 44 views
0

有沒有辦法檢查某個列的值是否在多行中相同?Mysql - 檢查多行的特定列是否相同

我需要檢查客戶是否在我的數據庫中放置了多個訂單。

如果我做我的選擇

SELECT * FROM orders WHERE email = '[email protected]' 

這可能會產生

OrderID Product Amount email 
50  Apples 1  [email protected] 
50  Oranges 1  [email protected] 
50  Bananas 1  [email protected] 
91  Apples 1  [email protected] 

所以我需要檢查,如果訂單ID是一樣的,在這些行。

但是如何?

回答

1

使用count()函數和GROUP BY子句caunt多少條記錄都按順序編號:

select email, orderid, count(*) as number_orders_per_orderid 
from orders 
where email = '[email protected]' 
group by email, orderid 

或者,如果要統計訂單的用戶已作出的號碼,然後使用count(不同的...)與組:

select email, count(distinct orderid) as number_of_orders 
from orders 
where email = '[email protected]' 
group by email 
1

您可以通過組辦,並具有

select id, count(*) from orders group by id 
WHERE email = '[email protected]' 
having count(*) > 1 
0

你可以得到一個「只要Ø NE」如果客戶有一個ORDERID 你可以得到一個‘不止一個’如果客戶有使用CASE ... WHEN

下面的例子

SELECT email,COUNT(*) as number_order , 
(CASE WHEN count(*)=1 THEN "Just one" WHEN count(*)>1 THEN "More than one" END) AS number_order_status 
FROM orders GROUP BY email 
多個ORDERID
相關問題