在子组中的每条记录上的MySQL子查询

时间:2012-07-23 11:09:42

标签: php mysql group-by

这是之前问题的更高级续集。

Here's a link to an SQLFiddle to make things a bit clearer

我需要返回类似的内容(对于每个位置):

  

底层
  ---------------
  车库
   - 散热器
  厨房
   - 电磁炉
   - 冰箱

将会有更多级别,但如果我能够开始,我希望能够根据需要进一步发展。

由于

3 个答案:

答案 0 :(得分:2)

由于SQL无法返回上面格式化的嵌套记录,因此您只需要返回一个按行排序然后按sub_location排序的查询。您将获得每行重复locationsub_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";      
}

答案 1 :(得分:2)

您可以使用此解决方案显示已知深度的层次结构:

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

对于更多级别,您可以在子选择中添加更多联合。


SQLFiddle Demo


示例结果集:

Ground Floor
-----> Garage
----------> Radiator
-----> Kitchen
----------> Cooker
----------> Fridge
First Floor
-----> Bedroom
----------> Radiator
----------> Taps
Second Floor
-----> Bathroom
----------> Shower
----------> Taps
----------> Toilet
Third Floor

答案 2 :(得分:1)

如果是在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

http://sqlfiddle.com/#!2/db932/9