2017-03-27 24 views
1
サブクエリ

にメインクエリを参照注文ラインでMySQLは:注文と注文でORDER_LINE</p> <p>Iのようなデータを持っている:私は2つのテーブルを持っている

id | name | order_date 
1 | order 1| 2014-01-01 
2 | order 2| 2015-01-01 
3 | order 3| 2016-01-01 

があるデータ等:

id | Order_id | order_status |status_date 
1 | 1  | New   | 2014-01-01 
2 | 1  | Shipped  | 2014-10-01 
3 | 2  | New   | 2015-01-01 
4 | 2  | Canceled  | 2015-03-01 
5 | 3  | New   | 2016-01-01 
6 | 3  | Canceled  | 2016-02-01 

オーダーラインには日付とステータスがあります

今、いくつの行にGivenステータスステータスがあるか知りたいある月/年。 たとえば、2014-08でステータス「新規」の値1、2016-03で「キャンセル済み」の値2が必要です。 それを報告するには、私は何とかすべての注文の最新のorder_line行を取得し、それを報告する必要があります。私は何とか私は推測する親クエリにサブクエリをリンクする必要があるだろうが、私が行う方法を見つけ出すことはできません

select orderline.* from orders o 
join (select * from orderline 
     where order_id = 1 
     and status_date = (select max(status_date) 
         from orderline 
         where order_id = 1 
         and status_date < MAKEDATE(2018, 8))) as orderline on orderline.order_id = o.id 
where o.id = 1; 

:私はちょうど単一の注文を持っている場合、私はこのような最新のオーダーラインを得ることができますこの。サブクエリの1を "where order_id = o.id"に置き換えようとすると、エラーコード:1054が返されます。 'where句'に 'o.id'という不明な列があります

サンプルを作成/テーブル:

CREATE TABLE orders 
    (`id` int(11), `name` varchar(7), `order_date` datetime) 
; 

INSERT INTO orders 
    (`id`, `name`, `order_date`) 
VALUES 
    (1, 'order 1', '2014-01-01 00:00:00'), 
    (2, 'order 2', '2015-01-01 00:00:00'), 
    (3, 'order 3', '2016-01-01 00:00:00') 
; 



CREATE TABLE orderline 
    (`id` int, `Order_id` int, `order_status` varchar(8), `status_date` datetime) 
; 

INSERT INTO orderline 
    (`id`, `Order_id`, `order_status`, `status_date`) 
VALUES 
    (1, 1, 'New', '2014-01-01 00:00:00'), 
    (2, 1, 'Shipped', '2014-10-01 00:00:00'), 
    (3, 2, 'New', '2015-01-01 00:00:00'), 
    (4, 2, 'Canceled', '2015-03-01 00:00:00'), 
    (5, 3, 'New', '2016-01-01 00:00:00'), 
    (6, 3, 'Canceled', '2016-02-01 00:00:00') 
; 

答えて

2

私はあなたがこのような何かをしたいと思う:

select ol.order_status, count(*) 
from orderline ol 
where ol.status_date = (select max(ol2.status_date) 
         from orderline ol 
         where ol2.order_id = ol.order_id and 
           ol2.status_date < '2014-08-01' 
         ) 
group by ol.order_status; 

これは、特定の日付(サブクエリの日付)のように与えられた状態でのご注文の行数を返します。

関連する問題