1

maybe someone can help me.

I have 2 sql tables:

 // groups
 | id_group   | namegroup |
 +------------+-----------+
 | 30         | s         |


 // contacts
 | name | group |
 +------+-------+
 | juan | s     |

I need to DELETE a group from ID, but no has contacts associated with it. I test the following query but doesnt work.

DELETE
FROM group
WHERE id_group = 30
AND (
    SELECT
        count(*) AS id
    FROM contacts co
    INNER JOIN GROUP c ON co. GROUP = c.namegroup
    WHERE   c.id_group = 30
) = 0

Thanks

2
  • Do you want to delete all groups which don't have any associated contacts? Or you just want to delete group having id = 30 only if it's not associated to any contact?
    – 1000111
    May 24, 2016 at 4:03
  • only group having id=30 only if its not associated to any contact. thanks!
    – gmyb
    May 24, 2016 at 4:41

2 Answers 2

0

You can try the following query if you want to delete group having ID = 30 only if the group is not associated to any contact :

Query #1:

DELETE
`groups`
FROM `groups`
LEFT JOIN contacts
ON contacts.`group` = `groups`.namegroup
WHERE `groups`.id_group = 30
AND contacts.`group` IS NULL;

And if you want to delete all groups which don't have any associated contact then try the following query instead:

Query #2:

 DELETE
 `groups`
 FROM `groups`
 LEFT JOIN contacts
 ON contacts.`group` = `groups`.namegroup
 WHERE contacts.`group` IS NULL;
0
0

If you define firigen key mysql will handle this issue and you do not need to do anything

In these cases(without forigen key) i usually first run following query:

select count(*) as id from contacts co inner join group c on co.group=c.namegroup where c.id_group=30

And say to user which if they can delete or not and if he could delete that row:

delete from group where id_group=30

I tried to find a solution like query which you had but could not and suggest this solution for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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