如何循环JOIN

时间:2013-04-02 04:04:43

标签: php mysql

我在图片中有这个表数据。它基本上由地点名称和在同一个表中包含的其他地方组成。字段belongs_to指的是其他地方的id

enter image description here

以下是我正在使用的查询:

         SELECT A.type,
                A.name_en AS name_A,
                B.name_en AS name_B,
                C.name_en AS name_C

                FROM address AS A
                LEFT JOIN address AS B ON A.belongs_to = B.id
                LEFT JOIN address AS C ON B.belongs_to = C.id 
                WHERE A.name_en LIKE '%".$_GET['name']."%'
                "

当我输入“sy”时,它能正常工作:

[type] = city
[name_A] =sydney
[name_B] =NSW
[name_C] =australia

然而,当我输入“ken”时,它会让我:

[type] =suburb
[name_A] = kensington
[name_B] =sydney
[name_C] = NSW

它错过了澳大利亚。我想让它变得灵活,以便我获取type_order1belongs_to0的国家/地区名称的所有数据。我一直在尝试搜索循环技术,但找不到好的参考。告诉我如果您有另外的建议要完成这项工作,或者如果您认为我的解决方案是正确的,请帮我解决循环问题或者请参考有关MySQL循环的详细参考。

3 个答案:

答案 0 :(得分:3)

用户加入没有任何问题。您的情况基本上取决于您的WHERE条件。请提供表格的结构,或者您可以尝试:

SELECT A.type,
                A.name_en AS name_A,
                B.name_en AS name_B,
                C.name_en AS name_C

                FROM address AS A
                LEFT JOIN address AS B ON A.belongs_to = B.id
                LEFT JOIN address AS C ON B.belongs_to = C.id 
                WHERE A.name_en LIKE '%".$_GET['name']."%' or A.id=1

答案 1 :(得分:0)

SELECT A.name_en AS name_A, NULL AS TYPE    

FROM tablename1 AS A
LEFT JOIN tablename1 AS B ON A.belongs_to = B.id                
WHERE A.name_en LIKE '%ken%' OR A.belongs_to = B.id OR A.belongs_to = 0

UNION ALL

SELECT NULL AS name_A, C.type
FROM tablename1 AS C
WHERE c.name_en LIKE '%ken%'

希望这会对你有所帮助

答案 2 :(得分:0)

您选择保留链接数据的技术称为“邻接列表”。一般来说,没有办法“循环”随机深度A.L.要查看从'kensington'到'australia'的项目,您需要再加入查询。您必须为每个额外的行添加一个连接。

寻找替代技术,例如“嵌套列表”和“物化路径”。 或者在PHP中使用循环来遍历Adjacency List项目。