如何组合两个查询,以便一个查询的结果将在另一个查询中使用?

时间:2014-06-17 17:29:26

标签: mysql sql

如何在另一个查询中使用一个查询的结果?

我需要这样的东西:

SELECT 
    id,
    orderDate,
    goodsCount = (
            SELECT
                    count(*) as Count
            FROM 
                    ShopOrderGoods
            WHERE 
                    order_id = so.id
    )
FROM 
    ShopOrders

ShopOrder是一个表,我存储订单。 ShopOrderGoods是我存储每个订单商品的表格。

我可以使用服务器语言+2(如果ShopOrders表中只有1行)查询。

我先查询:

select * from ShopOrders

在服务器语言中,我正在处理此查询的结果:

$rowset = $resultOfQuery;
foreach($rowset as $order) {
    // do another query: select count(*) as Count from ShopOrderGoods where order_id = $order->id;
    // put result to $count variable
    // output $order->orderDate, $order->id, $count
}

所以我将进行1 + N次查询(N是ShopOrder表中的行数) - 一点也不好。

所以我想只使用1个查询来做到这一点。预期结果是:

+++++++++++++++++++++++++++
+ id + orderDate  + count +
+ 1  + 2014-12-12 + 15    +
+++++++++++++++++++++++++++
+ 2  + 2014-11-11 + 10    +
+++++++++++++++++++++++++++
+ 10 + 2010-10-10 + 8     +
+++++++++++++++++++++++++++

对我来说这不是必要的!也许你可以说我应该在谷歌输入什么。谢谢。

更新

是否可以将此订单的所有商品的总和价格添加到结果集中?每个表的价格存储在另一个表中 - SuppliersGoods

预期结果集是:

+++++++++++++++++++++++++++++++++++
+ id + orderDate  + count +  sum +
+++++++++++++++++++++++++++++++++++
+ 1  + 2014-12-12 + 15    + 7500  +
+++++++++++++++++++++++++++++++++++
+ 2  + 2014-11-11 + 10    + 3000  +
+++++++++++++++++++++++++++++++++++
+ 10 + 2010-10-10 + 8     + 2000  +
+++++++++++++++++++++++++++++++++++

在表格中,供应商商品价格存储在字段price中。表ShopOrderGoods中将好计数指定为字段count

更新2

SQL我试过(工作):

SELECT 
    so.id,
    so.orderDate,
    s.name as supplierName,
    COUNT(*) as goodsCount,
    SUM(sg.price*sop.count) as goodsSum
FROM 
    ShopOrders as so
INNER JOIN
    Contracts as c
    ON c.id = so.contract_id
INNER JOIN 
    Suppliers as s
    ON s.id = c.supplier_id 
INNER JOIN 
    ShopOrderGoods as sop
    ON sop.shopOrder_id = so.id
INNER JOIN 
    SuppliersGoods as sg
    ON sop.supplierGood_id = sg.id 
GROUP BY
    so.id, so.orderDate, s.name 

好吗?看起来有些怪异:D

2 个答案:

答案 0 :(得分:2)

看起来似乎不需要嵌套查询; inner join group by就足够了{{3}}。

试试这个:

SELECT 
    so.id,
    so.orderDate,
    COUNT(sog.id) AS goodsCount
FROM 
    ShopOrders so
INNER JOIN 
    ShopOrderGoods sog
ON 
    sog.order_id = so.id
GROUP BY
    so.id, so.orderDate

更新尝试这样的方法来获取每个订单的总价(我猜的是列名):

SELECT 
    so.id,
    so.orderDate,
    COUNT(sog.id) AS goodsCount,
    SUM(sg.price * sog.count) AS sum
FROM 
    ShopOrders so
INNER JOIN 
    ShopOrderGoods sog
ON 
    sog.order_id = so.id
INNER JOIN 
    SupplierGoods sg
ON 
    sog.good_id = sg.id
GROUP BY
    so.id, so.orderDate

答案 1 :(得分:1)

您所描述的是一个加入:

SELECT id, orderDate, count(*) as goodsCount
FROM ShopOrders so
JOIN ShopOrderGoods sog
   ON sog.order_id = so.id
GROUP BY id, orderDate;