发现了一种表连接新的写法,以前还没有这样写过或者见别人写过。跟同学聊天他们公司却很多人这样写,看来真的要学学sql了
表
CREATE TABLE `t_book` ( `FId` int(11) NOT NULL, `FName` varchar(50) DEFAULT NULL, `FYearPublished` int(11) DEFAULT NULL, `FCategoryId` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_book -- ---------------------------- INSERT INTO `t_book` VALUES ('1', 'About J2EE', '2005', '4'); INSERT INTO `t_book` VALUES ('2', 'Learning Hibernate', '2003', '4'); INSERT INTO `t_book` VALUES ('3', 'Two Cites', '1999', '1'); INSERT INTO `t_book` VALUES ('4', 'Jane Eyre', '2001', '1'); INSERT INTO `t_book` VALUES ('5', 'Oliver Twist', '2002', '1'); INSERT INTO `t_book` VALUES ('6', 'History of China', '1982', '2'); INSERT INTO `t_book` VALUES ('7', 'History of England', '1860', '2'); INSERT INTO `t_book` VALUES ('8', 'History of America', '1700', '2'); INSERT INTO `t_book` VALUES ('9', 'History of The World', '2008', '2'); INSERT INTO `t_book` VALUES ('10', 'Atom', '1930', '3'); INSERT INTO `t_book` VALUES ('11', 'RELATIVITY', '1945', '3'); INSERT INTO `t_book` VALUES ('12', 'Computer', '1970', '3'); INSERT INTO `t_book` VALUES ('13', 'Astronomy', '1971', '3'); INSERT INTO `t_book` VALUES ('14', 'How To Singing', '1771', '5'); INSERT INTO `t_book` VALUES ('15', 'DaoDeJing', '2001', '6'); INSERT INTO `t_book` VALUES ('16', 'Obedience to Authority', '1995', '6'); CREATE TABLE `t_category` ( `FId` int(11) NOT NULL, `FName` varchar(50) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_category -- ---------------------------- INSERT INTO `t_category` VALUES ('1', 'Story'); INSERT INTO `t_category` VALUES ('2', 'History'); INSERT INTO `t_category` VALUES ('3', 'Theory'); INSERT INTO `t_category` VALUES ('4', 'Technology'); INSERT INTO `t_category` VALUES ('5', 'Art'); INSERT INTO `t_category` VALUES ('6', 'Philosophy');
书表
目录表
任务:查询出每种类目的 类目名称、类目id,最晚的出版年份
一般的想法是,将book表通过类目id进行分组,求出max(出版年份),再和类目表进行join即可:
select c.*,A.maxPub from t_category c left join ( select b.FCategoryId cid ,max(b.fyearpublished) maxPub from t_book b group by b.FCategoryId)A on c.fid=A.cid
但是看见新的写法是这样的:
select c.fid,c.FName,(select max(b.FYearPublished) from t_book b where b.FCategoryId=c.FId) maxPub from t_category c
查询出来结果是一样的
这个SELECT语句首先检索FId、FName两个字段,而第三个字段不是一个列二是一个子查询。这个子查询位于主查询的内部,它返回一类图书的最新出版年份。因为聚合函数仅返回一行记录,所以这满足标量子查询的条件。通过WHERE语句,这个子查询也被连接到外部的SELECT查询语句中,因为这个连接,MAX(FYearPublished)将返回每类图书的最新出版年份。
记录一下