mysql - 一个sql中的两个SQL查询

标签 mysql

我有两个查询,我想将它们组合在一起,以便将两个不同表中的信息获取到一个数组中。

 $stmt = $pdo->query("SELECT * FROM Product WHERE id=". $productid);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $itemData = array(
            'id' => $row['id'],
            'name' => $row['name'],
            'unitprice' => $row['unitprice'],
            'quantity' => 1
        );

我想将其添加到同一个 stmt

SELECT size FROM ProductDetails where id=".$productid);

然后获得 $itemData 数组,如下所示:

$itemData = array(
                'id' => $row['id'],
                'name' => $row['name'],
                'size' => $row['size'],
                'unitprice' => $row['unitprice'],
                'quantity' => 1
            );

有没有可能的方法来做到这一点? 谢谢。

最佳答案

您想在此处使用左连接

The MySQL LEFT JOIN clause allows you to query data from two or more database tables. The LEFT JOIN clause is an optional part of the SELECT statement, which appears after the FROM clause.

所以在你的例子中:

SELECT * FROM Product 
LEFT JOIN ProductDetails ON ProductDetails.product_id = Product.product_id
WHERE id=". $productid

关于mysql - 一个sql中的两个SQL查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48904450/

相关文章:

mysql - 如何删除字段-Mysql 查询中间的文本

php - 应用程序在提取数据时挂起

PHP 通知 : Undefined variable

php - 两个 SQL 查询返回奇怪的结果

java - 2 个 POJO 类扩展了一个基类,其中每个类都映射到唯一的表。为什么 hibernate 查询在“字段列表错误”中创建​​未知列 ''?

mysql - Sql 查询进行 pandas 因式分解。 group by 后的累积和?

mysql - 在 MySQL 中寻找合作

php - 使用连接表更新

php - 从 HTML 表单中发布任意数量的记录

php - Laravel - session 不与数据库驱动程序保持一致