Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL join to grab data from same table via intermediate table

Tags:

sql

Could someone help me with building the following query. I have a table called Sites, and one called Site_H. The two are joined by a foreign key relationship on page_id. So the Sites table contains pages, and the Site_H table shows which pages any given page is a child of by having another foreign key relation back to the site table with a column called ParentOf.

So, a page can be have another page as a parent. Other data is stored in the Site_H table such as position etc, hence why it is separated out.

I would like a query that returns the details of a page along with the details of its parent page. I just cant quite think about how to structure the SQL.

Thanks

like image 358
Sergio Avatar asked Feb 25 '26 08:02

Sergio


1 Answers

SELECT  sc.*, sp.*
FROM    Sites sc
JOIN    Site_H h
ON      h.parentOf = sc.page_id
JOIN    Sites sp
ON      sp.page_id = h.page_id
WHERE   sc.page_id = @mypage
like image 191
Quassnoi Avatar answered Feb 27 '26 23:02

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!