2016-07-21 11 views
0

私はトランザクションと項目という2つのテーブルを使用しています。取引MySQL内部ジョイントと複数の条件

C_ID - State - Time 
1 Start 2016-07-13 16:02:42 
1 Passed 2016-07-13 20:28:21 
2 Passed 2016-07-11 17:39:13 
3 Passed 2016-07-07 20:23:00 
4 Start 2016-07-01 13:19:54 
4 Passed 2016-07-01 17:37:41 
5 Start 2016-07-07 16:16:21 
5 Passed 2016-07-07 21:04:01 
6 Passed 2016-07-07 21:11:39 
7 Passed 2016-07-08 20:30:46 

は表2:

表1以下を参照して後述するようにアイテム

C_No - C_ID 
C1 - 5 
C2 - 3 
C3 - 9 
C4 - 7 
C5 - 6 
C6 - 8 
C7 - 2 
C8 - 4 
C9 - 10 
C10 - 1 

私は、これらのテーブルを結合して出力を必要としたいと思います。 2つのテーブルを結合することに加え

出力

C_No - State - Time 
C10 - Start 2016-07-13 16:02:42 
C10 - Passed 2016-07-13 20:28:21 
C8 - Start 2016-07-01 13:19:54 
C8 - Passed 2016-07-01 17:37:41 
C1 - Start 2016-07-07 16:16:21 
C1 - Passed 2016-07-07 20:00:01 

、私は国家と時間のフィルタをしたいです。条件は(State = 'Start'とTime < = 17:00)、(State = 'Passed'、Time < = 21:00)

です。合格。

私は次のクエリ

{SELECT distinct(c.C_No), p.State, p.Time FROM Items c 
inner join Transitions p on p.c_id = c.c_id and date(p.Time) between '2016-07-01' and CURRENT_DATE() 
and ((p.State = 'Start' and time(p.Time) <= '17:00:00') or p.State = 'Passed') 
order by c.C_No, State;} 

SQLFiddleを使用し、質問に追加されました。

+0

はsqlfiddleを作成して、URLを共有しています。私には少なくとも、私はそれなしで質問を試みることを迷惑にならないでしょう。しかし、それは私だけです。 – Drew

+0

http://sqlfiddle.com/#!9/f05f9f/6 – Chakde

+0

フィデルありがとうございました。私はチャンスを得る時を見ます。私はいくつかの人々を引き付けるように質問を修正しました。 – Drew

答えて

0

が選択c_no、状態、内部取引から時間がtransactions.c_id = items.c_id(状態= 'スタート' と右の上の項目に参加し、この文を試してみてください(時間、8)< = '17:00 :00 ')または(状態=' 合格」と右(時間、8)< = '21:00' :00)

0

アイデアを次のようにあなたのサンプルを用いて、あなたの質問に

with t_start as (
    select t2.c_no, t1.state, t1.time 
    from transactions t1 
    inner join items t2 on t2.c_id=t1.c_id 
    where t1.state='State' and time(t1.time)<='17:00:00' 
) t_passed as(
    select t2.c_no, t1.state, t1.time 
    from transactions t1 
    inner join items t2 on t2.c_id=t1.c_id 
    where t1.state='Passed' and time(t1.time)<='21:00:00' 
) t_total as(
    select * from t_start 
    union 
    select * from t_passed 
) 
select * from t_total order by c_no, state; 
0

データ、私はC1が結果に存在するはずだとは思わないので、C_ID = 5、そのStateは「合格」で、そのTimeは「2016-07-07 21:04:01」であり、条件に一致しません。だから、これを試してみてください。

select t2.C_No, t.`State`, t.`Time` 
from Transactions t 
join (
    select C_ID 
    from Transactions 
    where (State = 'Start' and time(`Time`) <= '17:00:00') 
    or (State = 'Passed' and time(`Time`) <= '21:00:00') 
    group by C_ID 
    having count(distinct State) > 1 
) t1 on t.C_ID = t1.C_ID 
left join Items t2 on t1.C_ID = t2.C_ID 
order by t2.C_No, t.`State`; 

SqlFiddle Demo

+0

あなたは揺れます。その良い仕事。ありがとうJPG – Chakde