我有一个包含以下列的 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 中完成,而无需通过爆炸等进行分块?
在 SQL 中使用逗号分隔的列表很尴尬。这是一种非规范化设计,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"];
}
}
像这样的东西:
$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'];
}
仅使用 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