0
 I have a simple structure of 2 tables: contacts and group_contacts. A contact can belong to one, many or no groups. I'm trying to write a select statement that will give me all the contacts that don't belong to group_id '123'. The negative, don't, has me confused. CREATE TABLE IF NOT EXISTS `contacts` ( `contact_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL) CREATE TABLE IF NOT EXISTS `group_contacts` ( `contact_id` bigint(20) unsigned NOT NULL, `group_id` int(11) unsigned NOT NULL) thanks 

4 Answers 4

4
select a.contact_id from contacts a, group_contacts b where b.group_id<>123 and b.contact_id=a.contact_id; 
Sign up to request clarification or add additional context in comments.

2 Comments

joining condition should be always in form clause to filter tables multiplications.
i am unable to understand your comment bro!!... what do you mean by form clause ??
3

You would have to proceed this in two macro-steps:

  1. First you would need to left outer join between contacts and group_contacts table so that all contacts that do and don't have any relevant relation in group_contacts table is selected
  2. Then in the where clause of group_contacts group_id of 123 should be loaded.

Comments

2
select * from contacts as ct left join group_contacts as gc on ct.contact_id=gc.contact_id where gc.group_id!=123 

Comments

1

try this

select * from contacts a left join group_contacts b on a.contact_id = b.contact_id where b.group_id !=123 

2 Comments

syntax error in query. please check.I am not sure we can use like "left join b group_contacts ".Alias name should be after table name
i fix thank you, it typo mistake b need to be after the table name ofcurse

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.