简体   繁体   English

算一个很复杂的选择mysql

[英]count a very complex select mysql

I have a very complex select that union 3 tables to show customer's last activities. 我有一个非常复杂的选择,即合并3表以显示客户的最近活动。

so: 所以:

select c.data, p.user, concat(c.user, ' buy your product') as logs from sell c inner join posts p on c.foto = p.id where p.user = ?
union all
select f.data, c.user, concat(c.user, ' asked you a question') as logs from questions f inner join cadastro c ON f.user = c.id where f.nick = ?
union all
select l.data, l.user, concat(l.user, ' like your product') as logs from likes l inner join posts p on l.post = p.id where p.user = ?
order by data desc

well, each of this tables has a row called SEEN . 很好, 每个表都有一个名为SEEN的行 it is a varchar set with 0 or 1 (0 the user has not seen the message, 1 the user has already seen it). 它是设置为0或1的varchar(0用户未看到该消息,1用户已看到该消息)。

What I want to add in this query is something to count the rows where seen = 0. 我想在此查询中添加的内容是对可见= 0的行进行计数。

I want to show: YOU HAVE 4 new alerts . 我想显示: 您有4个新警报

select count(*) will not work and will not count right (the seen set to 1). select count(*)将不起作用,也不会正确计数(可见设置为1)。

What can I do to count all this selects where seen = 0? 我该怎么做才能数所有看过的选择(= 0)?

Try this 尝试这个

select a.*, SUM(IF(a.seen='0', 1, 0)) as 'unseen_count' FROM (
    select c.data, p.user, concat(c.user, ' buy your product') as logs, seen from sell c inner join posts p on c.foto = p.id where p.user = ?
    union all
    select f.data, c.user, concat(c.user, ' asked you a question') as logs, seen from questions f inner join cadastro c ON f.user = c.id where f.nick = ?
    union all
    select l.data, l.user, concat(l.user, ' like your product') as logs, seen from likes l inner join posts p on l.post = p.id where p.user = ?
) as a
order by data desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM