我有两个查询,我想将它们组合在一起,以便将两个不同表中的信息获取到一个数组中。
$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/