按栏选择并取消

时间:2015-01-22 20:04:08

标签: mysql select group-by

我试图用这些表格进行困难查询:

服务

id_service             description                  cost
    1                  service 1                     20
    2                  service 2                     30
    3                  service 3                     25

记录

id_history               status              id_service    
    1                      0                     1
    2                      1                     1
    3                      2                     1
    4                      3                     1
    5                      0                     2
    6                      4                     1
    7                      1                     2
    8                      2                     2
    9                      0                     3
   10                      1                     3
   11                      3                     2

我需要知道哪些服务不完整(状态!= 4)并按最近的更新分组。也许,像这样:

id_history              status            id_service          description
    11                    3                   2                service 2
    8                     2                   2                service 2
    7                     1                   2                service 2
    5                     0                   2                service 2
    10                    1                   3                service 3
    9                     0                   3                service 3

这是我目前的查询:

SELECT a.*, b.descripcion
FROM history a 
   JOIN service b ON a.id_service = b.id_service
WHERE a.status != 4

GROUP BY a.id_service    

ORDER BY a.id_history DESC

每个id_service只返回一行:

ID_HISTORY  STATUS  ID_SERVICE  DESCRIPTION
    9         0         3       service 3
    5         0         2       service 2
    1         0         1       service 1

2 个答案:

答案 0 :(得分:0)

您可以使用not exists来取消状态为4的服务

select h.id_history, h.status, h.id_service, s.description
from 
service s
join history h
on h.id_service = s.id_service
where not exists ( select 1 from history h2
                   where h.id_service = h2.id_service
                   and h2.status = 4
                 )
order by h.id_history desc, h.id_service desc

如果您想要每个服务的最新状态,那么您可以在子查询中使用group by

select h.id_history, h.status, h.id_service, s.description
from 
service s
join (
select max(status) as status, id_service
from history
group by id_service
)t
on s.id_service =t.id_service
and t.status  !=4
join history h
on h.status = t.status
and h.id_service = t.id_service
order by h.id_history desc

答案 1 :(得分:0)

我认为你不能使用" Group by"像这样的东西:

SELECT a.*, b.descripcion
FROM history a 
   JOIN service b ON a.id_service = b.id_service
WHERE a.status != 4
ORDER BY a.id_history DESC