I have this table:
affiliate_id | parent_affiliate_id |
---|---|
4 | 5 |
3 | 4 |
2 | 3 |
1 | 2 |
6 | 5 |
8 | 7 |
10 | 9 |
12 | 11 |
What I need is to make a query that shows all parents of an affiliate.
Expected outcome:
affiliate_id | all_parent_id |
---|---|
1 | 2, 3, 4, 5 |
2 | 3, 4, 5 |
3 | 4, 5 |
… | … |
10 | 9 |
12 | 11 |
I’m trying to use this query but without success:
$aff = 1;
foreach( $wpdb->get_results("
SELECT A.*
FROM {$wpdb->prefix}table A
JOIN
( SELECT affiliate_id
, parent_affiliate_id
FROM {$wpdb->prefix}table
WHERE $aff IN(affiliate_id, parent_affiliate_id)
) B
ON A.affiliate_id = B.affiliate_id
AND A.parent_affiliate_id = B.parent_affiliate_id
" ) as $key => $row) {
$subaff1 = $row->parent_affiliate_id;
echo 'Affiliate Id: '. $aff; echo ' - Parent: '. $subaff1; echo '<br/>';
}
What am I doing wrong?
Thanks in advance.
EDITED
Maybe i solved in part
using this code
SELECT affiliate_id, (SELECT GROUP_CONCAT( parent_affiliate_id) from affiliates B where B.affiliate_id BETWEEN A.affiliate_id AND B.parent_affiliate_id) AS all_parent_id FROM affiliates A
Show me all parents of every affiliate id
but i need to show too the parent of an affiliate
that have only one parent
You can test it here
https://www.db-fiddle.com/f/dKBfxUpb8fBXLTQqRKbN2B/1
2
Answers
You can use
GROUP_CONCAT
and a subquery like the following:You can test it here https://www.db-fiddle.com/f/5WRvcMBwbwCJhTtpX9rt4v/2
Here you can find more information. Keep it simple.
It could be solved by means of recursive Common Table Expressions if available (MySQL 8.0, MariaDB starting with 10.2.2) as follows:
It could be tested here https://www.db-fiddle.com/f/h18jBgh2322J6fj5XRofKu/1