Php MySQL-将表结果转换为行
我有一张这种格式的桌子Php MySQL-将表结果转换为行,php,mysql,sql,Php,Mysql,Sql,我有一张这种格式的桌子 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
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);
?>
编辑2:
解决办法可能是这样
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
我不知道该数据结构是如何有用的,但听起来您想要的是:
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)
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)