这是我对getting-the-last-record-inserted-into-a-select-query
的另一个问题的跟进我正在尝试编辑一个查询,Andrea非常友好地帮助我昨天哪个页面工作得很好,但是我试图创建一个类似的查询而没有太多运气。
我需要的是每个电路板显示电路板名称,与该电路板相关的主题和消息的数量以及最后一条消息的用户,主题和日期(确实有效)
我需要的是获取电路板名称,主题和消息计数
这是我的表结构
CREATE TABLE `boards` (
`boardid` int(2) NOT NULL auto_increment,
`boardname` varchar(255) NOT NULL default '',
PRIMARY KEY (`boardid`)
);
CREATE TABLE `messages` (
`messageid` int(6) NOT NULL auto_increment,
`topicid` int(4) NOT NULL default '0',
`message` text NOT NULL,
`author` varchar(255) NOT NULL default '',
`date` datetime(14) NOT NULL,
PRIMARY KEY (`messageid`)
);
CREATE TABLE `topics` (
`topicid` int(4) NOT NULL auto_increment,
`boardid` int(2) NOT NULL default '0',
`topicname` varchar(255) NOT NULL default '',
`author` varchar(255) NOT NULL default '',
PRIMARY KEY (`topicid`)
);
以及我根据Andrea为我做的查询得出的查询。此查询在boardname中输出的内容,主题和消息的数量(即使有5个也是1),主题作者和messagecount(不需要),作者和最后一篇文章的日期(需要) )但不是所需的主题名称
SELECT b.boardname, count( DISTINCT t.topicname ) AS topics, count( lm.message ) AS message, t.author as tauthor,
(select count(message) from messages m where m.topicid = t.topicid) AS messagecount,
lm.author as lauthor, lm.date
FROM topics t
INNER JOIN messages lm
ON lm.topicid = t.topicid AND lm.date = (SELECT max(m2.date) from messages m2)
INNER JOIN boards b
ON b.boardid = t.boardid
GROUP BY t.topicname
这是我的原始查询,它可以完成我想要的但是获得第一个帖子,而不是最后一个
SELECT b.boardid, b.boardname, count( DISTINCT t.topicname ) AS topics, count( m.message ) AS message, m.author AS author, m.date AS date, t.topicname AS topic
FROM boards b
INNER JOIN topics t ON t.boardid = b.boardid
INNER JOIN messages m ON t.topicid = m.topicid
INNER JOIN (
SELECT topicid, MAX( date ) AS maxdate
FROM messages
GROUP BY topicid
) test ON test.topicid = t.topicid
GROUP BY boardname
ORDER BY boardname
对此非常感激的任何帮助
答案 0 :(得分:5)
您需要根据ORDER BY子句定义“LAST”。完成后,您只需撤消订单的方向,然后将LIMIT 1
添加到查询中。
答案 1 :(得分:2)
SELECT b.*, m.*, t,*
(
SELECT COUNT(*)
FROM topics ti
WHERE ti.boardid = b.boardid
) AS topiccount,
(
SELECT COUNT(*)
FROM topics ti, messages mi
WHERE ti.boardid = b.boardid
AND mi.topicid = ti.topicid
) AS messagecount
FROM boards b
LEFT JOIN
messages m
ON m.messageid = (
SELECT mii.messageid
FROM topics tii, messages mii
WHERE tii.boardid = b.boardid
AND mii.topicid = tii.topicid
ORDER BY
mii.date DESC
LIMIT 1
)
LEFT JOIN
topics t
ON t.topicid = m.topicid