我一直在尝试从多个表中选择数据,而我通过左连接加入的另一个表中的 id 计数进行排序。一切都很好,除了计数增加 600something 而不是每行一个。
正如我在类似问题中看到的那样,我尝试将 distinct 放入 count 语句中,但唯一的结果是冻结数据库。
表:
CREATE TABLE IF NOT EXISTS `places` (
`PlaceId` int(10) NOT NULL AUTO_INCREMENT,
`Name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`AreaId` int(10) NOT NULL DEFAULT '1',
PRIMARY KEY (`PlaceId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=0;
CREATE TABLE IF NOT EXISTS `places_descriptions` (
`DescId` int(45) NOT NULL AUTO_INCREMENT,
`PlaceId` int(10) NOT NULL,
`Description` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`DescId`),
KEY `PlaceId` (`PlaceId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=0;
CREATE TABLE IF NOT EXISTS `places_hits` (
`HitId` int(45) NOT NULL AUTO_INCREMENT,
`PlaceId` int(45) NOT NULL,
PRIMARY KEY (`HitId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=0;
询问:
SELECT
p.PlaceId,
p.Name,
pd.Description,
COUNT(ph.HitId) AS numHits
FROM
places_descriptions AS pd,
places AS p
LEFT JOIN places_hits AS ph
ON (p.PlaceId = ph.PlaceId)
WHERE
(p.PlaceId = pd.PlaceId) AND
(p.AreaId = 1)
GROUP BY
p.PlaceId,
p.Name,
pd.Description
ORDER BY
numHits DESC,
p.PlaceId
LIMIT 0, 10
有任何想法吗?谢谢!