对每个对话框的消息进行计数

时间:2016-01-23 02:20:46

标签: mysql sql select

我需要进行一个查询,它会返回每个用户对话框的消息计数。我试图自己做,但它给了我所有对话框的消息数。 这是我的查询,其中包含我需要的参数。

SELECT COUNT(*)
FROM message, dialog 
WHERE (dialog.username LIKE 'acid') 
AND (message.checkms=0) 
AND (message.messender NOT LIKE 'acid') 
AND (dialog.iddialog=message.iddialog)

这是结果。请帮忙! enter image description here

CREATE TABLE `users` ( 
`username` varchar(45) CHARACTER SET utf8 NOT NULL, 
`enabled` bit(1) NOT NULL,
`password` varchar(60) CHARACTER SET utf8 NOT NULL, 
`name` varchar(30) CHARACTER SET utf8 NOT NULL,
`surname` varchar(30) CHARACTER SET utf8 NOT NULL,
`email` varchar(50) CHARACTER SET utf8 NOT NULL,
`gender` varchar(30) CHARACTER SET utf8 NOT NULL,
`age` varchar(2) NOT NULL,
`weight` varchar(2) NOT NULL,
`height` varchar(3) NOT NULL,
`sport` varchar(50) CHARACTER SET utf8 NOT NUlL,
`place` varchar(400) CHARACTER SET utf8 NOT NULL,
`photo` varchar(100) NOT NULL,
PRIMARY KEY (`username`) 
) ENGINE=InnoDB DEFAULT CHARSET=UTF8; 

create table dialog
(
`iddialog` int NOT NULL auto_increment,
`reciever` varchar(50) CHARACTER SET utf8 NOT NULL,
`username`varchar(45) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY(`iddialog`),
foreign key (`username`) references users(`username`)
)ENGINE=InnoDB DEFAULT CHARSET=UTF8; 

create table message(
`idmessage` BIGINT not null auto_increment,
`text` varchar(300) character set utf8 NOT NULL,
`date` varchar(40) NOT NULL,
`iddialog` int NOT NULL,
`messender` varchar(50),
`checkms` boolean,
primary key (`idmessage`),
foreign key (`iddialog`) references dialog(`iddialog`)
)ENGINE=InnoDB DEFAULT CHARSET=UTF8; 

1 个答案:

答案 0 :(得分:2)

如果我理解正确,听起来你需要group by用户名:

SELECT d.username, COUNT(*)
FROM message m
    join dialog d on m.iddialog = d.iddialog
WHERE d.username = 'acid'
    AND m.checkms=0
    AND m.messender != 'acid'
GROUP BY d.username

几个快速笔记。最好使用更标准的ansi join语法。如果你没有使用通配符,也不需要使用like - 它相当于没有等号。

您的问题可能需要更多澄清。也许你还需要按d.iddialog分组。这将返回每个用户每个对话框的结果:

SELECT d.username, d.iddialog, COUNT(*)
FROM message m
    join dialog d on m.iddialog = d.iddialog
WHERE d.username = 'acid'
    AND m.checkms=0
    AND m.messender != 'acid'
GROUP BY d.username, d.iddialog