我当前的问题是尝试构建一个给定条件的查询,该查询赋予了我特定的数量。

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

我的查询如下:

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,则表示该项目未发布,因此卖方处于非活动状态。但是,在某些情况下,卖方可能拥有过去出售的商品,加上实时商品,因此即使product.is_published = 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;

关于mysql - 如何在特定情况下在SQL中使用IF THEN,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36265052/

10-13 05:32