简体   繁体   中英

Getting names of parents from mysql database

I have a database with parent names in one table. Columns:id, name. And in other table id, parent_id, name. In a search field i enter names. Lest say Bob, Alice and Tom. And I have to search in the database for parents where they have children named Bob, Alice and Tom. They could have more children, but they must have these three.

Lets say Edmund has children: Bob, Tom, Bart, Alice and Liza, Richard has Bob, Alice and Ned.

Given these names the database should return only Edmund.

How should I write a SQL query for this problem or should I do it with PHP ?

You could join children with their parents. In the WHERE clause you filter the given children names

WHERE c.name IN ('Bob', 'Alice', 'Tom')

Then you group this by parent id.

Not tested:

SELECT p.id, MAX(p.name), count(*)
FROM child AS c
JOIN parent AS p ON c.parent_id = p.id
WHERE c.name IN ('Bob', 'Alice', 'Tom')
GROUP BY p.id

Now you can use the parents whose count value equals the number of requested child names.

You need to define the table structure properly. You can try this out...

TableChildren
------------------
------------------
  Name      ParentID
  Bob         1
  Alice       1   
  Tom         1
  Jerry       2
  Jerry       1

ParentID is a foreign key in the children table. ParentID will be a primary key parent's table, which will look like:

TableParents
--------------
--------------
ID      Name  
1      Edmund   
2      Emma

This will mean that Bob,Alice and Tom are are children of Edmund. And Jerry have both Edmund and Emma as parents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM