I’m use to simple SQL queries and can’t get this one.
I have a members table that is set like so:
member_id | member_number | member_fname | member_name | member_parent_id | member_status
member_parent_id is a reference to member_id
- I need to get all the members where the member_parent_id is not null
- Get the member_number as an extra column for the parent for each members
So far I got results but can’t figure how to add the extra column for the parent member_number
SELECT members.member_id, member_id_parent, member_nbr, member_fname, member_name, member_note
FROM members
LEFT JOIN .... other table
LEFT JOIN .... other table
WHERE member_id_parent IS NOT NULL
AND member_status = 1
;
I have tried some example with WITH RECURSIVE
but could figure out the logic and do the proper corrections to make it work.
Thanks,
2
Answers
Use name aliases for the table. Here I use
m
for the member andp
for the parent:Here are the steps you can use to solve this.
You can create a
CTE
to get each member_id and member_number for all members in your table.The next step is to use the created
CTE
tojoin
with the query used to fetch theparent_member_number
.Here is a quick demo on
fiddble