2016-07-21 61 views
0

我使用兩個名爲事務和項目的表。參閱下面MySQL內部聯合和多個條件的情況下

表1:事務

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:產品

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

我想加入這些表和需要輸出如下所述;

輸出

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 

除了連接兩個表,我想在國家和時間的過濾器。條件是(國家='開始'和時間< = 17:00)和(國家='通過'和時間< = 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和分享網址。至少對我來說,如果沒有它,我不會費心嘗試。但是,這只是我。 – 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