如何在SQL中使用IF THEN,具体方案

时间:2016-03-28 15:05:57

标签: mysql sql

我目前的问题是尝试构建一个查询,该查询给出了一个特定计数的条件。

我需要提取在我们的网站上销售商品但目前没有列出商品的用户列表。结果应该是仅包含当前未发布的项目的用户列表。

我的查询如下:

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,他们也会出现,因为他们同时拥有这两件商品。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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;