2015-09-06 66 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 ... :( –