1

我一直在尝试从多个表中选择数据,而我通过左连接加入的另一个表中的 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

有任何想法吗?谢谢!

4

1 回答 1

0

乍一看,您的问题可能是您正在交叉连接 pd 和 p 因为没有 ON 子句。where 中的 placeId=placeId 通过过滤掉连接不准确的行来掩盖此问题,但最好将该条件置于 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 
于 2012-06-14T22:24:44.300 回答