2015-09-06 64 views
1

我有兩個表,(1)表客戶和(2)表客戶操作。
這是我的示例表:查詢加入mysql的日期

表客戶:

id_clients | name | id_user_created | id_user_owner 
    1  alfa   4    0 
    2  beta   4    0 
    3  charlie  5    0 

表客戶操作:

id_clients_action |  date_action | id_clients | id_user_created | id_user_owner 
     1   2015-09-04 17:09:37  1    4    0 
     2   2015-09-05 18:19:07  1    4    0 

,然後在一個形式,我有兩個輸入參數,從日期到日期。
這是我的情況:

Condition-1 : 
-id_user_created = 4 
-from date = 2015-09-01 00:00:00 
-end date = 2015-09-03 00:00:00 

我想這樣的結果:

id_clients | name | date 
    1  alfa null 
    2  beta null 

下一個條件:

Condition-2 : 
-id_user_created = 4 
-from date = 2015-09-01 00:00:00 
-end date = 2015-09-22 00:00:00 

我想這樣的結果:

id_clients | name | date 
    1  alfa 2015-09-04 17:09:37 
    1  alfa 2015-09-05 18:19:07 
    2  beta null 

下面是我的查詢,但是當我想從我的病情中得到結果時,我仍然有一個真實的日期。請給我一個真實的問題。

select B.id_clients, B.id_user_created, B.name, A.date_action as lastActionDate 
from clients_action as A 
right join clients as B on A.id_clients=B.id_clients 
where 
B.id_clients in 
(
    select id_clients 
    from clients_action where 
    date_action between '2015-09-01 00:00:00' and '2015-09-03 00:00:00' and id_user_owner = '0' 
) 
or 
B.id_clients in 
(
    select id_clients 
    from clients 
    where 
    id_user_created = '4' and id_user_owner = '0' 
) 

回答

0
select distinct 
a.id_clients,a.name, 
case when b.id_clients_action=2 then b.date_action else null end as date 
from clients a 
left join clients_action b on a.id_user_created=b.id_user_created 
+0

對不起,id_clients_action是DINAMIC ... :( –