我有新闻和新闻类别。许多关系(第三范式),如果新闻有更多的类别(例如,5,6,7, 10 ,20)没有选择(因为它对ex有10),我需要选择所有不属于id =10的新闻。(4,61,55) -选择。
它需要通过连接和一个查询来完成。
CREATE TABLE IF NOT EXISTS `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(333) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
INSERT INTO `news` (`id`, `name`) VALUES
(1, 'One '),
(2, 'Two');
CREATE TABLE IF NOT EXISTS `news_cat` (
`news_id` int(11) NOT NULL,
`cat_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `news_cat` (`news_id`, `cat_id`) VALUES
(1, 2),
(1, 5),
(2, 3),
(2, 4);-
SELECT * from news left join news_cat on news_cat.news_id = news.id and cat_id !=5返回这两个记录,我需要修改这个查询以只返回id = 2的新闻,因为id =2的新闻有cat_id =5
发布于 2014-07-21 23:07:40
select news.id
from news
join news_cat on news.id = news_cat.news_id
group by news.id
having sum(case when news_cat.cat_id = 10 then 1 else 0 end) < 1http://sqlfiddle.com/#!2/d61a0/1/0
发布于 2014-07-21 23:09:33
使用left join获取没有cat_id = 10的。
select a.*
from news a
left join news_cat b on b.cat_id = 10 and a.id = b.news_id
where isnull(b.news_id);小提琴
https://stackoverflow.com/questions/24876244
复制相似问题