【发布时间】:2014-05-29 15:26:49
【问题描述】:
我需要一些关于左连接语句的帮助,该语句没有做我认为应该做的事情,可能是错误的。
有两个表:
光盘:
CREATE TABLE `cd` (
`itemID` int(11) NOT NULL AUTO_INCREMENT,
`title` text NOT NULL,
`artist` text NOT NULL,
`genre` text NOT NULL,
`tracks` int(11) NOT NULL,
PRIMARY KEY (`itemID`)
)
贷款
CREATE TABLE `loans` (
`itemID` int(11) NOT NULL,
`itemType` varchar(20) NOT NULL,
`userID` int(11) NOT NULL,
`dueDate` date NOT NULL,
PRIMARY KEY (`itemID`,`itemType`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我想使用左连接选择所有不在贷款中的 cd,然后选择其中的到期日期为空
select
t.itemID,
t.artist as first,
t. title as second,
(select AVG(rating) from ac9039.ratings where itemType = 'cd' and itemId = t.itemID) as `rating avarage`,
(select COUNT(rating) from ac9039.ratings where itemType = 'cd' and itemId = t.itemID) as `number of ratings`
from
cd t left join loans l
on t.itemID = l.itemID
where l.itemType = 'cd' and l.dueDate is null;
然而,即使 cd 中有很多行的 itemID 不在贷款中,此表也会返回一个空表
现在我明白左连接应该保留右侧并用空值填充左侧的列 但是好像不是这样的,有大神能赐教吗?
【问题讨论】:
-
将 'where' 更改为 'and' 并将 'and' 更改为 'where'