Select 并按列丢弃
Select and DISCARD by COLUMN
我试图用这些表进行困难的查询:
服务:
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
每 returns 一行 id_service
:
ID_HISTORY STATUS ID_SERVICE DESCRIPTION
9 0 3 service 3
5 0 2 service 2
1 0 1 service 1
您可以使用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
我认为你不能使用 "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
我试图用这些表进行困难的查询:
服务:
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
每 returns 一行 id_service
:
ID_HISTORY STATUS ID_SERVICE DESCRIPTION
9 0 3 service 3
5 0 2 service 2
1 0 1 service 1
您可以使用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
我认为你不能使用 "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