如何加入我的“客户”和“消息”表?

时间:2010-09-22 09:04:11

标签: mysql

有两个表:

Clients
___________
idClient int
login varchar

Messages
___________
idMessage int
dateWakeup datetime
.... other fields

我需要每个客户端计算给定时间范围内表格中的条目数。我试过这样的事情:

SELECT c.login, count(m.idMessage) FROM Clients c, Messages m
where
    m.idClient=c.idClient and m.dateWakeup>'2010-09-01 00:00:01'
    and m.dateWakeup<'2010-10-01 00:00:01';

它不起作用。

3 个答案:

答案 0 :(得分:2)

使用COUNT(...)时,您必须GROUP BY您的结果:

SELECT c.login, count(m.idMessage)
FROM Clients c, Messages m
where m.idClient=c.idClient
and m.dateWakeup>'2010-09-01 00:00:01'
and m.dateWakeup<'2010-10-01 00:00:01'
GROUP BY c.login

答案 1 :(得分:0)

试试这个

SELECT c.login, count(m.idMessage) FROM Clients as c
INNER JOIN Messages as m
ON m.idClient=c.idClient
WHERE m.dateWakeup BETWEEN '2010-09-01 00:00:01' and '2010-10-01 00:00:01'

答案 2 :(得分:0)

SELECT c.login, count(m.idMessage) FROM Clients c, Messages m  
where m.idClient=c.idClient and m.dateWakeup>'2010-09-01 00:00:01' and
m.dateWakeup<'2010-10-01 00:00:01' GROUP BY c.login;

COUNT()等聚合函数需要GROUP ... BY