活跃且有帖子或文章的用户

时间:2019-01-30 09:19:19

标签: mysql sql

我想吸引所有创建或更新帖子或/和文章的活跃用户

user(id,...)
post(id, created_by_id, updated_by_id, ...)
article(id, created_by_id, updated_by_id, ...)

我认为我发现一个有效的SQL请求:

select u.id, u.firstname, u.lastname
from user u, article a, post p
where u.is_active = true and (u.id = a.created_by_id or u.id = p.created_by_id or u.id = a.updated_by_id or u.id = p.updated_by_id)
group by u.id

是否可以添加一个虚拟字段来说明用户是否只是活跃用户,或者他是否创建或更新了内容(文章或帖子)?像这样:

id - firstname - lastname - status

1  - John      - Doe      - active
2  - Bob       - One      - has content
3  - Alice     - Twotwo   - has content
4  - Luke      - Sky      - active

这是什么要求?

4 个答案:

答案 0 :(得分:1)

您可以显式使用联接而不是逗号分隔的联接,并使用联合

 select u.id, u.firstname, u.lastname
 from user u  join
 article a on u.id=a.created_by_id or u.id=a.updated_by_id
 where u.is_active = true 
 union
  select u.id, u.firstname, u.lastname
 from user u  
 join post p on u.id=p.created_by_id or u.id=p.updated_by_id
 where u.is_active = true  

答案 1 :(得分:1)

您必须加入表并使用CASE来创建新列:

select u.id, u.firstname, u.lastname,
case 
  when (a.created_by_id is not null) or (p.created_by_id is not null) then 'has content'
  else 'active'
end status
from user u left join article a 
on u.id=a.created_by_id or u.id=a.updated_by_id
left join post p on u.id=p.created_by_id or u.id=p.updated_by_id
where u.is_active = true

答案 2 :(得分:1)

您可以尝试使用case when表达式,并且最好使用显式连接而不是逗号分隔的连接

select u.id, u.firstname, u.lastname,
case when u.is_active = true then 'active' else 'has content' end as 'status'
from user u inner join article a on u.id = a.created_by_id or u.id = a.updated_by_id
inner join post p on u.id = p.created_by_id or u.id = p.updated_by_id
where u.is_active = true 

答案 3 :(得分:1)

这是可能的case语句。

 SELECT u.id, u.firstname, u.lastname,
    CASE WHEN a.created_by_id is null &&  a.updated_by_id is null &&  p.created_by_id is null &&  p.updated_by_id is null THEN 'active'
    ELSE 'has content' 
    END as 'status'
    FROM User u
    LEFT JOIN post p ON u.id = p.created_by_id OR  u.id = p.updated_by_id
    LEFT JOIN article a ON u.id = a.created_by_id OR  u.id = a.updated_by_id
    WHERE u.is_active = 1
    ORDER BY u.id