我一直在尝试从多个表中选择数据,而我按照我用左连接加入的附加表中的id计数排序。一切都很好,除了计数增加600something而不是每行一个。
我尝试了,因为我在类似的问题中看到将不同的内容放在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
有什么想法吗?谢谢!
答案 0 :(得分:0)
乍一看,您的问题可能是您正在交叉加入pd和p,因为没有ON子句。 placeId = placeId在where中通过过滤掉连接不准确的行来掩盖此问题,但最好将该条件置于ON中。过滤前实际存在的大量行可能会丢掉计数,但我不确定。
试试这个,开始:
SELECT
p.PlaceId,
p.Name,
pd.Description,
COUNT(ph.HitId) AS numHits
FROM
places_descriptions AS pd
INNER JOIN places AS p
ON p.PlaceId = pd.PlaceID
LEFT JOIN places_hits AS ph
ON (p.PlaceId = ph.PlaceId)
WHERE
(p.AreaId = 1)
GROUP BY
p.PlaceId,
p.Name,
pd.Description
ORDER BY
numHits DESC,
p.PlaceId