sql查询组在一个连接中

时间:2018-03-22 21:45:40

标签: mysql sql sql-server

我有几张桌子:

--> task: task_id, status, datetime, code
--> task_action: action_id, task_id, action_type, action_details, action_datetime

我还有一个action_type:ASSIGNED,其JSON为action_type{"assigned_to": "some_email_id"}

所以我想要的是statustask table所有列的所有任务:PROCESSING

并且相应的action_typeASSIGNED,其中包含最新日期时间,(任务可以有多个ASSIGNED action_type) 并查询assigned_to电子邮件ID。

只有最新的ASSIGNED action_type应与assigned_to中的给定电子邮件ID匹配 这是我尝试过的一个查询:

select task_action.task_id
     , max(action_datetime) as dt
     , action_details
as adt 
  FROM task_action
  JOIN task 
    on task.task_id = task_action.task_id 
 WHERE action_type = 'ASSIGNED' 
   and task.status = 'PROCESSING' 
   and JSON_VALUE(adt, '$.assigned_to') = 'someEmail'   
 GROUP 
    BY task_id

显然,这不起作用。我猜有些东西不见了。

2 个答案:

答案 0 :(得分:0)

在MySQL 5.7中,您可以使用:

WHERE ... adt->>'$.assigned_to' = 'someEmail'

如果您只使用->,则该值具有文字双引号。使用->>获取裸值。

阅读https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html了解详情。

答案 1 :(得分:0)

问题是您在task_action中搜索具有最大日期时间的行,而不仅仅是最大值。在SQL中表达这有点复杂。您可以搜索task_action,其中不存在具有更长日期时间的其他task_action:

WITH assigned_action as (
  select 
    task_id,
    action_datetime, 
    action_details 
  from 
    task_action 
  where
    action_type='ASSIGNED' and 
    JSON_VALUE(action_details, '$.assigned_to')='someEmail'
)

SELECT 
   t.task_id, 
   a.action_datetime as dt, 
   a.action_details as adt 
FROM 
  task t inner join (
    select *
    from 
      assigned_action a1
    where not exists (
      select * 
      from assigned_action a2
      where 
        a2.action_datetime > a1.action_datetime and
        a2.task_id = a1.task_id 
    )
  ) a on t.task_id = a.task_id
WHERE 
  t.status='PROCESSING'
相关问题