这是较早问题的更高级的续集。
我需要返回类似的东西(对于每个位置):
一楼
---------------
车库
-
暖气厨房
- 炊具
- 冰箱
会有比这更多的关卡,但如果我能开始,我希望能够根据需要走得更远。
谢谢
这是较早问题的更高级的续集。
我需要返回类似的东西(对于每个位置):
一楼
---------------
车库
-
暖气厨房
- 炊具
- 冰箱
会有比这更多的关卡,但如果我能开始,我希望能够根据需要走得更远。
谢谢
由于 SQL 无法返回您在上面格式化的嵌套记录,因此您只需要返回一个查询,该查询按楼层然后按 sub_location 对您的行进行排序。你会得到每一行的location
和sub_location
重复的,但是在你的应用程序代码循环中打印结果时,你可以像上面那样格式化它们。
SELECT
location.location_name,
sublocation.sub_location_name,
asset.asset_name
FROM
location
LEFT JOIN sub_location ON location.location_key = sublocation.location_key
LEFT JOIN assets ON sub_location.sub_location_key = assets.sub_location_key
ORDER BY
location.location_name,
sub_location.sub_location_name
在应用程序中循环遍历行集时,您只需在新位置或 sub_location 更改时打印它。格式化是在代码中完成的。
假设您的行都在数组中$rowset
:
// Store location, sub_location for each loop
$current_loc = "";
$current_subloca = "";
foreach ($rowset as $row) {
// If the location changed, print it
if ($row['location'] != $current_loc) {
echo $row['location_name'] . "\n";
// Store the new one
$current_loc = $row['location_name'];
}
// If the sub_location changed, print it
if ($row['sub_location'] != $current_subloc) {
echo $row['sub_location_name'] . "\n";
$current_subloc = $row['sub_location_name'];
}
echo $row['asset_name'] . "\n";
}
您可以使用此解决方案显示已知深度的层次结构:
SELECT a.name
FROM
(
SELECT
CONCAT('- - - - - - - - - -> ', a.asset_name) AS name,
CONCAT(c.location_key, c.location_name, b.sub_location_name, a.asset_name) AS orderfactor
FROM asset a
INNER JOIN sub_location b ON a.sub_location_key = b.sub_location_key
INNER JOIN location c ON b.location_key = c.location_key
UNION ALL
SELECT
CONCAT('- - - - -> ', a.sub_location_name),
CONCAT(b.location_key, b.location_name, a.sub_location_name)
FROM sub_location a
INNER JOIN location b ON a.location_key = b.location_key
UNION ALL
SELECT
location_name,
CONCAT(location_key, location_name)
FROM location
) a
ORDER BY a.orderfactor
对于更多级别,您可以在子选择中添加更多联合。
示例结果集:
Ground Floor
-----> Garage
----------> Radiator
-----> Kitchen
----------> Cooker
----------> Fridge
First Floor
-----> Bedroom
----------> Radiator
----------> Taps
Second Floor
-----> Bathroom
----------> Shower
----------> Taps
----------> Toilet
Third Floor
如果是在 MySQL5
SELECT L.location_name, GROUP_CONCAT(DISTINCT S.sub_location_name), GROUP_CONCAT(A.asset_name)
FROM location L
INNER JOIN sub_location S ON L.location_key = S.location_key
INNER JOIN asset A ON A.sub_location_key = S.sub_location_key
GROUP BY S.sub_location_name ORDER BY L.location_key