开发者

retrieving same column twice from a table

开发者 https://www.devze.com 2022-12-20 22:11 出处:网络
I have a table named \"address\", which has:开发者_开发技巧 id title parent_id ...fields. In the title column, the name of regions and districts are inserted. The regions have parent_id value

I have a table named "address", which has:

开发者_开发技巧
  • id
  • title
  • parent_id

...fields.

In the title column, the name of regions and districts are inserted. The regions have parent_id value of zero, and parent_id of the districts are id of the regions.

I want a query which display regions in one column and it's respective districts in another column.


You could join the table onto itself like this:

SELECT
   R.Title AS Region,
   D.Title AS District
FROM
   address R
INNER JOIN
   address D
   ON
   D.parent_id = R.id
   AND
   D.parent_id > 0
WHERE
   R.parent_id = 0

However your table structure is a bit odd, I would do some reading on database normalization.


Use something like the following:

Select r.Region, s.State 
from
    (Select id, title as Region from address where parent_id=0) as r,
    (Select id, title as State, parent_id from address where parent_id>0) as s
where s.parent_id = r.id

Its an ANSI SQL. You can further tune it for your need.

0

精彩评论

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