-3
我有一個表格式MySQL的 - 轉換表導致成行
id1 | id2 | id3 | id4 | id5
a | b | c | null | null
a | b | d | null | null
a | b |null | null | null
我需要的結果(a,b,c,d)
我做這個用PHP,但代碼太困難了......
<?php
$sql="SELECT t1.id as id1, t2.id AS id2, t3.id AS id3, t4.id AS id4, t5.id AS id5
FROM store_subcategory AS t1
LEFT JOIN store_subcategory AS t2 ON t2.parent_id = t1.id
LEFT JOIN store_subcategory AS t3 ON t3.parent_id = t2.id
LEFT JOIN store_subcategory AS t4 ON t4.parent_id = t3.id
LEFT JOIN store_subcategory AS t5 ON t5.parent_id = t4.id
WHERE (t1.root_id=$cat or t1.id=$cat) and t1.store_id=$id";
$result=$mysqli->query($sql);
$subid=array();
while($row=$result->fetch_assoc())
{
if($row["id1"]!=null) $subid[$row["id1"]]=1;
if($row["id2"]!=null) $subid[$row["id2"]]=1;
if($row["id3"]!=null) $subid[$row["id3"]]=1;
if($row["id4"]!=null) $subid[$row["id4"]]=1;
if($row["id5"]!=null) $subid[$row["id5"]]=1;
}
$subsarray=array();
foreach($subid as $key => $value)
{
array_push($subsarray, $key);
}
$subid=implode(",", $subsarray);
?>
感謝 PS:對不起,我的英語不好
編輯: 表是與5級
的層次化樹`store_subcategory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) DEFAULT NULL,
`it` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
EDIT2: 的解決方案可能是這個
SELECT * FROM (
SELECT DISTINCT(t1.id)
FROM store_subcategory AS t1
WHERE (t1.root_id=$cat or t1.id=$cat) and t1.store_id=$id
UNION
SELECT DISTINCT(t2.id)
FROM store_subcategory AS t1
LEFT JOIN store_subcategory AS t2 ON t2.parent_id = t1.id
WHERE (t1.root_id=$cat or t1.id=$cat) and t1.store_id=$id
UNION
SELECT DISTINCT(t3.id)
FROM store_subcategory AS t1
LEFT JOIN store_subcategory AS t2 ON t2.parent_id = t1.id
LEFT JOIN store_subcategory AS t3 ON t3.parent_id = t2.id
WHERE (t1.root_id=$cat or t1.id=$cat) and t1.store_id=$id
UNION
SELECT DISTINCT(t4.id)
FROM store_subcategory AS t1
LEFT JOIN store_subcategory AS t2 ON t2.parent_id = t1.id
LEFT JOIN store_subcategory AS t3 ON t3.parent_id = t2.id
LEFT JOIN store_subcategory AS t4 ON t4.parent_id = t3.id
WHERE (t1.root_id=$cat or t1.id=$cat) and t1.store_id=$id
UNION
SELECT DISTINCT(t5.id)
FROM store_subcategory AS t1
LEFT JOIN store_subcategory AS t2 ON t2.parent_id = t1.id
LEFT JOIN store_subcategory AS t3 ON t3.parent_id = t2.id
LEFT JOIN store_subcategory AS t4 ON t4.parent_id = t3.id
LEFT JOIN store_subcategory AS t5 ON t5.parent_id = t4.id
WHERE (t1.root_id=$cat or t1.id=$cat) and t1.store_id=$id
) AS t_group WHERE id IS NOT NULL
1.參見標準化 – Strawberry