:SQL - 次のように私はサンプルデータでは、次のMySQLのテーブルを持って再帰クエリ
id location parentid
1 UK 0
2 East Anglia 1
3 Cambridgeshire 2
4 Norfolk 2
5 Suffolk 2
6 East Midlands 1
7 Derbyshire 6
8 Leicestershire 6
9 EU Countries 0
10 Austria 9
11 Belgium 9
私は場所の名前で場所のリストを取得することができますが、場所は任意の親を含むべきであることにより、クエリを生成したいですロケーション。例えば
folk
の検索が返す必要があります:
id location
4 Norfolk, East Anglia, UK
5 Suffolk, East Anglia, UK
をEast
の検索が返す必要があります:
id location
2 East Anglia, UK
6 East Midlands, UK
をBel
の検索は返す必要があります:上記の私たちには
id location
11 Belgium
を連結していないものを除きますEU countries
明らかに以下のdoesntの仕事:あなたはこれだけが自己で行われ、親の場所をしたい場合は
select c.id, CONCAT_WS(', ', c.location, p.location, pp.location) as location
from tbl_locations c
outer left join tbl_locations p on p.id = c.parentid
outer left join tbl_locations pp on pp.id = p.parentid
where c.location like '%whatever%'
あなたは与えられたlocationidのテキストを返す関数を作ることができます。編集:関数は呼び出す必要がなくなるまでそれ自身を呼び出す必要があります(再帰の定義でもあります) – Doruk
http://guilhembichot.blogspot.co.uk/2013/11/with-recursive-and-mysql.html –
最大深度? – sumit