Skip to main content
added 49 characters in body
Source Link
Kamil
  • 11
  • 2

I have 2 tables. For simplicity, first table Parent contains only id and name. Other table Child contains id and parent_id.

I need a queryThere are going to select Parent bybe many parent rows with the same name. They will have different childrens, so I want to be able to select a parent row only if it has childs matching providedfrom the list of child id fieldI provide.

Let's say I want a Parent with name 'test' only if it has Childs with id (223, 224, 225). Only those, no more, no less.

So far I achieved this with following query:

SELECT p.*, GROUP_CONCAT(c.id) as childs
FROM `parent` p
    INNER JOIN `child` c ON p.id = c.parent_id
WHERE p.name = 'test'
GROUP BY p.name
HAVING childs = '223,224,225'
ORDER BY c.id

However I think it's not a good solution if it uses id concatenation

I have 2 tables. For simplicity, first table Parent contains only id and name. Other table Child contains id and parent_id.

I need a query to select Parent by name, only if it has childs matching provided list of child id field.

Let's say I want a Parent with name 'test' only if it has Childs with id (223, 224, 225). Only those, no more, no less.

So far I achieved this with following query:

SELECT p.*, GROUP_CONCAT(c.id) as childs
FROM `parent` p
    INNER JOIN `child` c ON p.id = c.parent_id
WHERE p.name = 'test'
GROUP BY p.name
HAVING childs = '223,224,225'
ORDER BY c.id

However I think it's not a good solution if it uses id concatenation

I have 2 tables. For simplicity, first table Parent contains only id and name. Other table Child contains id and parent_id.

There are going to be many parent rows with the same name. They will have different childrens, so I want to be able to select a parent row only if it has childs from the list I provide.

Let's say I want a Parent with name 'test' only if it has Childs with id (223, 224, 225).

So far I achieved this with following query:

SELECT p.*, GROUP_CONCAT(c.id) as childs
FROM `parent` p
    INNER JOIN `child` c ON p.id = c.parent_id
WHERE p.name = 'test'
GROUP BY p.name
HAVING childs = '223,224,225'
ORDER BY c.id

However I think it's not a good solution if it uses id concatenation

Source Link
Kamil
  • 11
  • 2

Selecting row by field and exact list of join id

I have 2 tables. For simplicity, first table Parent contains only id and name. Other table Child contains id and parent_id.

I need a query to select Parent by name, only if it has childs matching provided list of child id field.

Let's say I want a Parent with name 'test' only if it has Childs with id (223, 224, 225). Only those, no more, no less.

So far I achieved this with following query:

SELECT p.*, GROUP_CONCAT(c.id) as childs
FROM `parent` p
    INNER JOIN `child` c ON p.id = c.parent_id
WHERE p.name = 'test'
GROUP BY p.name
HAVING childs = '223,224,225'
ORDER BY c.id

However I think it's not a good solution if it uses id concatenation