MySQL查询用于搜索两个表的子集

时间:2011-07-21 08:54:07

标签: mysql

我有两张桌子:

CREATE TABLE IF NOT EXISTS `comments` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `photograph_id` int(11) NOT NULL,
    `created` datetime NOT NULL,
    `author` varchar(255) NOT NULL,
    `body` text NOT NULL,
    `email` varchar(255) NOT NULL,
    `liked` int(11) NOT NULL,
    PRIMARY KEY (`id`),
    KEY `photograph_id` (`photograph_id`)
)

而且:

CREATE TABLE IF NOT EXISTS `photographs` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `user_id` int(11) NOT NULL,
    `filename` varchar(255) NOT NULL,
    `type` varchar(100) NOT NULL,
    `size` int(11) NOT NULL,
    `caption` varchar(255) NOT NULL,
    `liked` int(11) NOT NULL,
    PRIMARY KEY (`id`),
    KEY `user_id` (`user_id`)
)

我无法将这两者合并为一个查询。在这个查询中,我希望对每张照片的评论数量进行排序调用。在“注释”表中,有列photograph_id,它链接到“照片”表中的照片ID。谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

对于包含1条或更多评论的照片,请执行以下操作:

SELECT p.id, COUNT(*) as commentcount FROM photographs p
INNER JOIN comments c ON (p.id = c.photograph_id)
GROUP BY p.id
ORDER BY commentcount DESC

如果您还想要评论为零的照片,请执行以下操作:

SELECT p.id, COUNT(c.id) as commentcount FROM photographs p
LEFT JOIN comments c ON (p.id = c.photograph_id)
GROUP BY p.id
ORDER BY commentcount DESC

答案 1 :(得分:0)

SELECT *,
       (SELECT COUNT(*) FROM comments
        WHERE photographs.id = ccomments.photograph_id)) commentcount
FROM photographs

这可能比join方法更快。也许。你需要进行实验。