简体   繁体   中英

Getting users of foreign key in mysql

I am playing around with php to get a REST api I can later use for an Ember app. So far everything works fine, I just got a question concerning MySQL. Since I'm more a frontend guy I'm not that familiar with it. I have a table in my database where some elements are parent elements of others. So every element has a parent, the topmost elements have the parent 0. Now i want my database to return all the values of an element and the element ids of which the element is the parent.

I want to combine

SELECT * FROM table WHERE id=exId

and

SELECT id FROM table WHERE parent_id=exId

And i want to return the children as an array so taht i can get JSON out of it like {"prop":"val", "children": [1,2,3,4]} . Is there a way to combine this or is it easier to do two queries and combine the arrays?

Join the two queries.

SELECT t1.prop, GROUP_CONCAT(t2.id) AS children
FROM table AS t1
JOIN table AS t2 ON t1.id = t2.parent_id
WHERE t1.id = :exId

children will be be a comma-separated list of IDs, which you can turn into an array using explode in PHP.

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