在下面的sql语句中:

 SELECT `keywords`.keyID, count(`keywords-occurencies`.keyID) as countOccurencies
                    FROM `keywords-occurencies`
                    LEFT JOIN `keywords`
                    ON `keywords-occurencies`.keyID = `keywords`.keyID
                    WHERE `keywords-occurencies`.`keyID` IN (1,2,3) AND date BETWEEN '2013/01/25' AND '2013/01/27'
                    GROUP BY `keywords`.`keyID`

如果keyid 3没有返回值,则不计算为0,也不包含在结果集中,并显示这样的结果
keyID countOccurencies
1       3
3       5

我想显示零结果如下
keyID countOccurencies
1       3
2       0
3       5

要测试的样本数据:
--
-- Table structure for table `keywords`
--

CREATE TABLE IF NOT EXISTS `keywords` (
  `keyID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `keyName` varchar(40) NOT NULL,
  PRIMARY KEY (`keyID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `keywords`
--

INSERT INTO `keywords` (`keyID`, `keyName`) VALUES
(1, 'testKey1'),
(2, 'testKey2');

-- --------------------------------------------------------

--
-- Table structure for table `keywords-occurencies`
--

CREATE TABLE IF NOT EXISTS `keywords-occurencies` (
  `occurencyID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `keyID` int(10) unsigned NOT NULL,
  `date` date NOT NULL,
  PRIMARY KEY (`occurencyID`),
  KEY `keyID` (`keyID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `keywords-occurencies`
--

INSERT INTO `keywords-occurencies` (`occurencyID`, `keyID`, `date`) VALUES
(1, 1, '2013-01-27'),
(2, 1, '2013-01-26');

--
-- Constraints for table `keywords-occurencies`
--
ALTER TABLE `keywords-occurencies`
  ADD CONSTRAINT `keywords@002doccurencies_ibfk_1` FOREIGN KEY (`keyID`) REFERENCES `keywords` (`keyID`) ON DELETE CASCADE ON UPDATE CASCADE;

最佳答案

要做的事情
您应该使用GROUP BY keywords-occurencies.keyID将其分组
您必须显示keywords-occurencies.keyID而不是keywords.keyID
计数keywords.keyID
(可选)使用ALIAS以便可以除去表名以外的反勾号
查询,

SELECT  a.keyID,
        count(b.keyID) AS countOccurencies
FROM    `keywords - occurencies` a
        LEFT JOIN `keywords` b
            ON a.keyID = b.keyID
WHERE   a.keyID IN ( 1, 2, 3 ) AND
        DATE BETWEEN '2013/01/25' AND '2013/01/27'
GROUP   BY a.keyID

更新1
根据示例记录,您需要执行以下操作:
交换表名
将此条件置于join的DATE BETWEEN '2013-01-25' AND '2013-01-27'子句上。
(可选)使用ON以便可以除去表名以外的反勾号
查询,
SELECT  a.keyID,
        count(b.keyID) AS countOccurencies
FROM    `keywords` a
        LEFT JOIN `keywords-occurencies` b
            ON a.keyID = b.keyID AND
               b.DATE BETWEEN '2013-01-25' AND '2013-01-27'
WHERE   a.keyID IN ( 1, 2, 3 )
GROUP   BY a.keyID

SQLFiddle Demo

09-09 22:13