我正在通过 UNION ALL 查询三个结构相同的表中的列
$sql="
(SELECT col1 FROM table1 WHERE col2 IN ('a','b','c') and col3 IS NOT NULL)
UNION ALL
(SELECT col1 FROM table2 WHERE col2 IN ('a','b','c') and col3 IS NOT NULL)
UNION ALL
(SELECT col1 FROM table3 WHERE col2 IN ('a','b','c') and col3 IS NOT NULL)
";
然后我使用 PDO 准备该语句并执行它
$stmt = $pdo->prepare($sql);
$stmt->execute();
$var = $stmt->fetchAll(PDO::FETCH_ASSOC);
我的问题是生成的数组:$var,使用整数键并将每个结果拆分为一个子数组。我需要每个表的结果都在自己的子数组中,最好以表名作为键。
目前:
print_r($var)
;给出:
Array
(
[0] => Array ( [col1] => asd)
[1] => Array ( [col1] => sdf)
[2] => Array ( [col1] => dfg)
[3] => Array ( [col1] => fgh)
)
我想要:
Array
(
[table1] => Array
(
[0] => Array ( [col1] => asd)
[1] => Array ( [col1] => sdf)
)
[table2] => Array
(
[0] => Array ( [col1] => asd)
)
[table3] => Array
(
[0] => Array ( [col1] => asd)
)
)
最佳答案
您无法在单个查询中执行此操作,但您可以使用 AS 关键字在列名称前加上相应的表名称作为前缀,之后您只需要预处理数组即可得到与您的类似的内容规范。
关于php - 如何调整 PDO fetchAll() 以设置为匹配多表查询中的表名称而创建的数组的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14930857/