开发者

Mysql use row data in same query to select another row?

开发者 https://www.devze.com 2023-03-11 07:59 出处:网络
Ive never had to use a query like this before but there must be away to do it without using 2 queries?

Ive never had to use a query like this before but there must be away to do it without using 2 queries?

Table : forum_categories

--------------------------------------
-- id ---- parent_id ---- name -------
--------------------------------------
   1          0           namehere1
   2          1           namehere2
   3          0           namehere3
   4          1           namehere4
   5          3           namehere5
开发者_开发知识库

I have the id for a sub cat and i want to select the row for the subcat then with the same query select the the row for the parent where parent_id = id for the parent row etc.

Whats the best way to do this?


You want something like

select a.id as child_id, a.name as child_name,
b.id as parent_id, a.name as parent_name
from forum_categories a
inner join forum_categories b
on a.parent_id = b.id

To restrict to your known id, add

where a.id = knownid
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号