2010-11-22 9 views
0

での声明私は、このSQLクエリを持っている:は、ネストされた「どこで」クエリ


select sum(qty) as 'total' from `sales_flat_quote_item` 
where item_id not in (
    select item_id from `sales_flat_quote_item_option` 
    where item_id in (
    select item_id from `sales_flat_quote_item` 
    where quote_id = 12670 
) 
    and code = 'is_gift' 
) 
and quote_id = 12670 and parent_item_id is null 

私の仕事は、JOIN句を使用して、このクエリを作成しています。よく質問自体は非常に奇妙です。 sales_flat_quote_itemは、クエリとサブクエリの両方で使用されます。これはいくつかの効率的な問題を引き起こす。

私はSQLのエキスパートではないので、私はあなたに尋ねています。私は自分自身でネストしたselectクエリの1つのlvlを処理できますが、この状況で何をすべきかわかりません。

我々は、MySQL DBエンジンvを使用して5.1


私はこのようにそれを作ることができました:。


select A.qty, A.item_id from `sales_flat_quote_item` as A 
where A.item_id not in 
(
    select B.item_id from 
    `sales_flat_quote_item_option` as B 
    inner join `sales_flat_quote_item` as C 
    on C.item_id = B.item_id 
    where B.code = 'is_gift' and 
    C.quote_id = 834 
) 
and A.quote_id = 834 and A.parent_item_id is null 

は、任意のサブクエリを使用せずにそれを作るために、それは可能ですか?

答えて

1

これを処理するには、内側から作業する必要があります。最も内側のクエリが返すものを見つけ出し、その結果をwhere句にマッチさせ、最初に到達するまで続けます。 「= is_gift quote_idが12670.

select item_id 
from `sales_flat_quote_item_option` 
where item_id in (Previous Result Set) 
and code = 'is_gift' 

である。これは、あなたのitem_idは、前のリストとコード列に含まれるのitem_idだのリストを与えるところ

select item_id 
from `sales_flat_quote_item` 
where quote_id = 12670 

これはあなたのitem_idのリストを与えるのですITEM_IDは、前回の結果セットではなく、12670のquote_idを持っており、parent_iteを持っていない総 『'

select sum(qty) as 'total' 
from `sales_flat_quote_item`  
where item_id not in (Previous Result Set) 
and quote_id = 12670 and parent_item_id is null 

これを数量フィールドの合計を返し、名前を』 m_id。

あなたの質問を再作成するには十分ですが、まだ問題が残っていれば私はコメントを投稿し、上記の情報(テーブルのデザインとは異なる)を与えて書き直すことができるかどうかを確認します。

+0

よく '(前回の結果セット)のitem_idとcode = 'is_gift''がnullを返す\' sales_flat_quote_item_option \ 'からitem_idを選択してください... – Ventus

+0

そのままそのまま実行しないと教えてください。以前の結果セットは私が「前のクエリの結果を得て、ここに置く」と言っていました。 – JonVD

+0

私はあなたが知って遅れていない;)私はちょうどいくつかの領域を節約するためにあなたのコードを貼り付ける。 2番目のレベルのクエリはnullを返すquote_id = 12670 :) – Ventus

関連する問題