MySQL / PHP查询以反转关系

时间:2013-08-29 17:37:07

标签: php mysql sql

我有一个包含以下列的mysql表:

ID      Units
1       1234,6543,9876
2       1234,6543
3       6543
4       9876
5       0987

我想颠倒关系以获得这样的输出:

Unit    IDs
1234    1,2
6543    1,2,3
9876    1,4
0987    5

我想知道这是否可以在查询或某些php中完成,而不会通过爆炸等进行分块?

3 个答案:

答案 0 :(得分:1)

在SQL中使用以逗号分隔的列表是awkward。这是一种非规范化设计,SQL不适合处理这种格式的数据。

我会将所有数据提取回PHP并在那里进行操作。

$id_per_unit = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  $unit_array = explode(",", $row["Units"]);
  foreach ($unit_array as $unit) {
    $id_per_unit[$unit][] = $row["Id"];
  }
}

答案 1 :(得分:0)

这样的事情:

$query = "SELECT `Unit`, `IDs` FROM `table` ORDER BY `Unit`";
$data = mysqli_query($con, $query);

$prev_unit = '';
while ($row = mysqli_fetch_array($data)) {
    if ($prev_unit != $row['Unit']) {
      // echo a new row with the new unit and then ID
    } else {
      // echo just the ID in the same row, this unit is the same as the last one.
    }
  $prev_unit = $row['Unit'];
}

答案 2 :(得分:0)

只有SQL,你可以这样做:

SELECT unit , GROUP_CONCAT(id)
FROM (
    SELECT id,substring_index(Units,',',1) AS unit
    FROM Table1
    UNION
    SELECT id,REPLACE(
           REPLACE(SUBSTRING_INDEX(Units,',',2),SUBSTRING_INDEX(Units,',',1),'')
              ,',','') AS unit
    FROM Table1
    UNION
    SELECT id,REPLACE(
           REPLACE(SUBSTRING_INDEX(Units,',',3),SUBSTRING_INDEX(Units,',',2),'')
              ,',','') AS unit
    FROM Table1) AS UNITS
WHERE unit != ''
GROUP BY unit

参见 SQLFIDDLE