0

I have news and news category. MANY MANY relation (3rd normal form) I need to select all news which NOT in category with id = 10 if news have more categories (ex, 5,6,7,10,20) not select (because it has 10) if for ex. (4,61,55) - select.

It needs to be done with JOIN and one query.

    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

returns both records, i need to modify this query to return only news with id = 2, because news with id = 2 have cat_id = 5

3
  • 1
    Please add your exact table structure, example data, expected output and the query you tried.
    – juergen d
    Jul 21, 2014 at 23:01
  • 1
    Into the question please and well formatted
    – juergen d
    Jul 21, 2014 at 23:03
  • 1
    At the start of your question it looks like you want to filter out news posts having category 10. Then you say category 5. Is it 10 or 5? Jul 21, 2014 at 23:12

2 Answers 2

2
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) < 1

http://sqlfiddle.com/#!2/d61a0/1/0

1
  • Replace the 10 in the case statement with 5 if that's the actual category you want to filter out. That would give you a result of just news id #2. Jul 21, 2014 at 23:13
1

Use left join to get ones that do not have 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);

fiddle

2
  • i need without subqueries Jul 21, 2014 at 23:10
  • @SuleymanovRashid, I just realized the subquery was not needed :)
    – Fabricator
    Jul 21, 2014 at 23:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.