算一个非常复杂的选择mysql

时间:2015-09-28 07:24:15

标签: php mysql

我有一个非常复杂的选择,联合3个表来显示客户的最后活动。

这样:

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

嗯,每个表都有一行名为SEEN 。它是一个varchar设置为0或1(0用户没有看到消息,1用户已经看过它。)

我想在此查询中添加的内容是计算所见的行= 0。

我想展示:您有4个新提醒

select count(*)将不起作用,并且不会向右计数(看到设置为1)。

我可以做些什么来计算所有这些选择where = 0?

1 个答案:

答案 0 :(得分:0)

试试这个

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