2016-03-28 132 views
0

我當前的問題是嘗試構建一個查詢,給定一個條件它給了我一個特定的計數。如何在SQL中使用IF THEN,具體場景

我需要提取已在我們網站上銷售商品的用戶列表,但目前沒有任何商品列出。結果應該是僅有當前未發佈項目的用戶列表。

我的查詢如下:

select `products`.`id` as 'product id', `users`.`id` as 'user id', 
`users`.`full_name` as 'user full name',`users`.`email` as 'user email' 
(CASE WHEN `products`.`is_published` = 1 
    THEN count(`products`.`ìs_published`) = 0 
    ELSE END) 
from `users`,`products` 
and `users`.`is_active` = 1 
and `products`.`user_id` = `users`.`id` 
group by `users`.`id` 
order by 'user id' asc; 

對於背景下,如果products.is_published = 1則意味着用戶有一個活項目,如果是= 0,這意味着該項目沒有公佈,因此賣家不活躍。但是,有些情況下,賣家可能有過去已售出的物品,再加上活物品,因此即使products.is_published = 0也會顯示出來,因爲它們都有。

任何幫助將不勝感激。

+4

請編輯您的問題,並提供樣本數據和期望的結果。 –

+0

我澄清了我的問題,讓我知道這是否有幫助。 @GordonLinoff – ramoncacho

+0

好像你的'WHERE'在這裏丟失了。爲什麼不是你當前的查詢工作?我們無法訪問您的數據,也無法分辨,因此我們需要樣本數據和期望結果。檢查使用「新」的'JOIN' [語法](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins。 aspx)。 –

回答

0

,你可以指望用戶項目中的子查詢,像這樣:

select users.id as 'user id' 
, users.full_name as 'user full name' 
, users.email as 'user email' 
, (select count(1) from products where is_published = 1 and user_id = users.id) as 'count of published' 
from users 
Where is_active = 1 
order by 'user id' asc; 

,如果你需要,只有當用戶已經發布的產品試試這個數:

select users.id as 'user id' 
, users.full_name as 'user full name' 
, users.email as 'user email' 
, pc.c as 'count of published' 
from users 
inner join (select user_id, count(1) as c from products where is_published = 1 group by user_id) as pc on pc.user_id = users.id 
Where is_active = 1 
order by 'user id' asc; 
+0

謝謝Adam!這有效,現在對我來說唯一的另一件事就是過濾掉「已發佈數量」大於0的數字。這會爲我提供正確數量的非活動用戶。 – ramoncacho

+0

如果您需要非活動用戶列表,請從不存在的用戶中選擇*(從is_published = 1和user_id = users.id的產品中選擇1)... –