简体   繁体   English

一个SQL中有两个SQL查询

[英]Two SQL queries in one sql

I have two queries which I want to combine together in order to get information from two different tables into one array. 我有两个查询,我想将它们组合在一起,以便将来自两个不同表的信息合并到一个数组中。

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

I would like to add this to the same stmt 我想将此添加到同一stmt

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

and then have the $itemData array as follows: 然后具有$ itemData数组,如下所示:

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

Is there a possible way to do this? 有没有办法做到这一点? Thank you. 谢谢。

You want to use a left join here 您想在这里使用左联接

The MySQL LEFT JOIN clause allows you to query data from two or more database tables. MySQL LEFT JOIN子句允许您从两个或多个数据库表中查询数据。 The LEFT JOIN clause is an optional part of the SELECT statement, which appears after the FROM clause. LEFT JOIN子句是SELECT语句的可选部分,出现在FROM子句之后。

So in your example: 因此,在您的示例中:

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

Try using a join: 尝试使用联接:

SELECT p.*, pd.size
FROM Product p
INNER JOIN ProductDetails pd
    ON p.id = pd.productid;

Use a join in your SQL query and only select the fields you need. 在SQL查询中使用联接,然后仅选择所需的字段。

$stmt = $pdo->query("SELECT p.id, p.name, pd.size, p.unitprice FROM Product as p INNER JOIN ProductDetails as pd ON p.id = pd.productid WHERE p.id=". $productid);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $itemData = array(
        'id' => $row['id'],
        'name' => $row['name'],
        'size' => $row['size'],
        'unitprice' => $row['unitprice'],
        'quantity' => 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM