2016-05-26 5 views
0

私はサブクエリを持つクエリを持っています。両方ともユーザーIDのリストを返します。内部クエリでは、特定の時間枠内の特定の場所で現金を使用したすべての顧客を私に与えます。MySQL:2つのクエリ間で異なる値を取得

第2は、特定の日付の後に注文され、現金を支払い方法として使用しなかった最初のユーザーIDをすべて選択します。

select distinct c.user_id 
from (
    select distinct o.user_id 
    from `order` as o 
    inner join payments as p on p.id = o.id 
    where o.orderplaced_ts > "2016-01-01 00:00:00" 
    and o.store_id = "12" 
    and p.payment_method = "Cash" 
) as c 
inner join `order` as o on c.user_id = o.user_id 
inner join `payments` as p on o.id = p.id 
where o.orderplaced_ts > "2016-03-13 00:00:00" 
and o.store_id = "12" 
and p.payment_method != "Cash" 

にはどうすれば2016-03-13以来、何のためにしなかったユーザー間のクロスを入手できます。参考のため

: - これは

両方のクエリを設定呼ん160ユニークなIDを返し組み合わせ -

select distinct o.user_id 
from `order` as o 
inner join payments as p on p.id = o.id 
where o.orderplaced_ts > "2016-01-01 00:00:00" 
and o.store_id = "12" 
and p.payment_method = "Cash" 

は236のユニークなIDを返しますBこのセットを呼び出すIDがセットAである

とはnotセットB

+0

変更最後の2' INNER JOIN'間の句ではありませんを使用し、残念ながら、0行を返す@alexの 'WHERE'節 – Alex

+0

の終わりに' p.id IS NULL'条件を追加してください。 – Bardworx

+0

私に証拠を示す – Alex

答えて

0

私はあなたの側からいくつかのsqlfiddleを取得することをお勧めします。

しかし、私は持っていないことから、ここでの私の試みです:

select distinct c.user_id 
from (
    select distinct o.user_id 
    from `order` as o 
    inner join payments as p on p.id = o.id 
    where o.orderplaced_ts > "2016-01-01 00:00:00" 
    and o.store_id = "12" 
    and p.payment_method = "Cash" 
) as c 
LEFT JOIN `order` as o 
ON c.user_id = o.user_id 
    AND o.orderplaced_ts > "2016-03-13 00:00:00" 
    AND o.store_id = "12" 
LEFT JOIN `payments` as p 
ON o.id = p.id 
    AND p.payment_method != "Cash" 
WHERE p.id IS NULL 
+0

ありがとう。最初は、私は脳のおならを持って、明示的にあなたの指示に従いました。私はその後、私は底なしの条件を取り除かなければならないことに気づきました – Bardworx

+0

実際には* JOINのために*削除*を* ONに移してはいけません – Alex

0

は `LEFT JOIN`には、2つのクエリ

select distinct o.user_id 
from `order` as o 
inner join payments as p on p.id = o.id 
where o.orderplaced_ts > "2016-01-01 00:00:00" 
and o.store_id = "12" 
and p.payment_method = "Cash" 
and o.user_id not in (

    select distinct c.user_id 
    from (
     select distinct o.user_id 
     from `order` as o 
    inner join payments as p on p.id = o.id 
     where o.orderplaced_ts > "2016-01-01 00:00:00" 
     and o.store_id = "12" 
     and p.payment_method = "Cash" 
    ) as c 
    inner join `order` as o on c.user_id = o.user_id 
    inner join `payments` as p on o.id = p.id 
    where o.orderplaced_ts > "2016-03-13 00:00:00" 
    and o.store_id = "12" 

) 
関連する問題