求助一个 SQL 语句:多表查询用 GROUP BY 缺少数据怎么解决

2017-01-02 03:38:14 +08:00
 jookr

主表 ads_location


CREATE TABLE IF NOT EXISTS `ads_location` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `flag` varchar(50) NOT NULL DEFAULT '',
  `display` tinyint(1) NOT NULL DEFAULT '1',
  `total` tinyint(3) NOT NULL DEFAULT '0',
  `rank` tinyint(3) NOT NULL DEFAULT '99',
  PRIMARY KEY (`id`),
  KEY `display` (`display`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;

INSERT INTO `ads_location` (`id`, `name`, `flag`, `display`, `total`, `rank`) VALUES
(1, 'index1', 'i_big_img1', 1, 0, 99),
(2, 'index2', 'i_big_img2', 1, 0, 99),
(3, 'index4', 'i_big_img3', 1, 2, 99),
(4, 'list1', 'l_big_img1', 1, 0, 99);

关联表 ads_content


CREATE TABLE IF NOT EXISTS `ads_content` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lid` int(11) NOT NULL,
  `name` varchar(255) NOT NULL DEFAULT '',
  `href` varchar(255) NOT NULL,
  `title` varchar(50) NOT NULL,
  `src` varchar(255) NOT NULL,
  `alt` varchar(50) NOT NULL,
  `desc` varchar(255) NOT NULL DEFAULT '',
  `begin_time` int(11) NOT NULL,
  `end_time` int(11) NOT NULL,
  `rank` tinyint(3) NOT NULL DEFAULT '99',
  PRIMARY KEY (`id`),
  KEY `lid` (`lid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;



INSERT INTO `ads_content` (`id`, `lid`, `name`, `href`, `title`, `src`, `alt`, `desc`, `begin_time`, `end_time`, `rank`) VALUES
(1, 3, '1', '1', '1', '1', '1', '', 1483295605, 1483295629, 1),
(3, 3, '2', '2', '2', '2', '2', '', 1483295633, 1514831633, 127);

查询

SELECT l . * , MIN( c.begin_time ) begin_time, MAX( c.end_time ) end_time FROM ads_location l, ads_content c WHERE l.id = c.lid GROUP BY l.id ORDER BY l.rank DESC LIMIT 100

以上语句才能得出一条数据。

我希望 ads_location 有几条数据,查询结果就显示几条,应该怎么写呢?

先谢谢各位了 新年快乐!

2907 次点击
所在节点    问与答
1 条回复
skydiver
2017-01-02 06:46:33 +08:00
你这样查询相当于 inner join ,第二个表里只有 lid3 这一条存在,自然结果就只有一条。

改成 left join 第二个表就可以了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/331657

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX