合并两个 PDO 查询的结果

发布于 2024-10-28 20:10:56 字数 445 浏览 2 评论 0原文

我有以下行:

$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。

我该怎么做呢?或者,我对使用 JOIN 查询相当陌生,有没有办法在 SQL 中完成此操作,而不会使 piP3Components.typeID 结果出现在不同的列中?

谢谢。

I have the following line:

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

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.

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?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

·深蓝 2024-11-04 20:10:56

你有两个选择。

首先,如果您从每个表中选择的列具有相同的列类型,您可以 使用 < code>UNION

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

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

$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);

You have two options.

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文