合并两个PDO查询的结果 [英] Combine Results from Two PDO queries

查看:92
本文介绍了合并两个PDO查询的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一行:

$products = $dbh->query("SELECT piP2Components.typeID, invTypes.typeName FROM piP2Components INNER JOIN invTypes ON piP2Components.typeID = invTypes.typeID ORDER BY invTypes.typeName ASC;");

我有另一个表piP3Components,我想对它运行相同的查询,并将结果添加到$ products变量中.结果是一个PDOStatement对象,我不能简单地使用array_push.

I have another table, piP3Components and I would like to run the same query on it and have the results added to the $products variable. As the result is a PDOStatement object I can't simply array_push.

我将如何去做?另外,我对使用JOIN查询还很陌生,是否有一种方法可以在SQL中完成此任务而又不会将piP3Components.typeID结果放在不同的列中?

How would I go about doing this? Alternatively, I'm fairly new to using JOIN queries, is there a way to accomplish this in SQL without having the piP3Components.typeID results in a different column?

谢谢.

推荐答案

您有两个选择.

首先,如果要从每个表中选择的列具有相同的列类型,则可以使用UNION :

First, if the columns you're picking from each table have identical column types, you can use a UNION:

SELECT foo, bar, baz FROM something WHERE ...
UNION ALL
SELECT qux AS foo, meta AS bar, syntactic AS baz FROM elsewhere WHERE ...

第二,您可以运行两个查询,然后获取每个查询的结果并将它们放置在单个数组中,稍后在处理结果时使用该数组而不是语句句柄:

Second, you can run both queries, then fetch the results for each and place them in a single array, using that array later instead of the statement handle when processing the results:

$results = array();

$sth_a = $pdo->prepare(...);
$sth_a->execute(...);
while($row = $sth_a->fetch(PDO::FETCH_ASSOC))
    $results[] = $row;

$sth_b = $pdo->prepare(...);
$sth_b->execute(...);
while($row = $sth_b->fetch(PDO::FETCH_ASSOC))
    $results[] = $row;

print_r($results);

这篇关于合并两个PDO查询的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆