有这样的表
IdRows | UpperLevelIdRows | CategoriesName |
-------------------------------------------------
2 | 0 | Transport
4 | 2 | Cars
12 | 4 | Alfa Romeo
查询
SELECT IdRows AS IdRows1, CategoriesName AS CategoriesName1 FROM categories
WHERE UpperLevelIdRows = ?
UNION
SELECT IdRows AS IdRows2, CategoriesName AS CategoriesName2 FROM categories
WHERE UpperLevelIdRows = ?
占位符数据
Array
(
[0] => 2
[1] => 4
)
所以
SELECT IdRows AS IdRows1 .... WHERE UpperLevelIdRows = 2
和
SELECT IdRows AS IdRows2 .... WHERE UpperLevelIdRows = 4
结果期望得到像
这样的数组 [0] => Array
(
[IdRows1] => 4
[CategoriesName1] => Cars
)
[1] => Array
(
[IdRows2] => 12
[CategoriesName2] => Alfa Romeo
)
但是得到像这样的数组
[0] => Array
(
[IdRows1] => 4
[CategoriesName1] => Cars
)
[1] => Array
(
[IdRows1] => 12
[CategoriesName1] => Alfa Romeo
)
而不是IdRows2
,请参阅IdRows1
如果我只执行第二个SELECT IdRows AS IdRows2 ...
,则按预期[CategoriesName2] => Alfa Romeo
我的错误在哪里?需要纠正什么?
从我想要创建的数据中选择/选项框。像
首先选择框
echo '<select name="upper_level_id0" id="upper_level_id0" >
<option value="'.$IdRows1.'">'.$CategoriesName1.'</option>
</select>';
第二个选择框
echo '<select name="upper_level_id1" id="upper_level_id1" >
<option value="'.$IdRows2.'">'.$CategoriesName2.'</option>
</select>';
目前使用交易找到解决方案。遍历所有SELECT ...
$db->beginTransaction();
foreach ( $sql_get_id_name as $k_sql => $val_sql ) {
$stmt_get_id_name = $db->prepare( $val_sql );
$stmt_get_id_name->execute( array( $data_get_id_name[$k_sql] ) );
$id_name[] = $stmt_get_id_name->fetchAll(PDO::FETCH_ASSOC);
}
$roll_back = $db->rollBack();
答案 0 :(得分:1)
使用此选择
select cp.IdRows p_id, cp.UpperLevelIdRows p_parent_id, cp.CategoriesName p_name,
cc.IdRows p_id, cc.UpperLevelIdRows c_parent_id, cc.CategoriesName c_name
from categories cc left join categories cp on cp.IdRows = cc.UpperLevelIdRows
where cc.UpperLevelIdRows = 4
这样你就会得到父母的所有儿子。结果中的前3列是父级(在您的行数据中它将是汽车),第二列是其子级(在您的行数据中是阿尔法罗密欧)