我有一个这种格式的表
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
答案 0 :(得分:0)
我不知道这个数据结构是如何有用的,但它听起来像你想要的东西:
SELECT DISTINCT(ID)
FROM
(select distinct(id1) AS ID
from table
UNION
select distinct(id2) AS ID
from table
UNION
select distinct(id3) AS ID
from table)