我有下表:
id name priority urgency output
1 mark 0 0 A
2 mark 0 1 B
3 mark 0 0 C
4 erik 0 0 D
5 erik 0 0 E
我希望为列表中的每个名称增加具有最高紧急度的条目的优先级,或者如果存在相同的紧急情况,则增加列表中最旧的条目的优先级。在此之后,我希望列表中每个名称的优先级最高的条目。因此,在第一次运行后,表格应如下所示:
id name priority urgency output
1 mark 0 0 A
2 mark 1 1 B
3 mark 0 0 C
4 erik 1 0 D
5 erik 0 0 E
我想从数据库中得到的是每个名称具有最高优先级的链接,因此:
id name priority urgency output
2 mark 1 1 B
4 erik 1 0 D
那里有人知道这是怎么做的吗?
答案 0 :(得分:2)
更新查询:
Update user_priority u1,
(
select min(id) as id
from user_priority inner join
(select name,max(urgency)as max_urg
from user_priority
group by name) as user_urgency on (user_priority.name = user_urgency.name
and user_priority.urgency = user_urgency.max_urg)
group by user_priority.name) u2
set priority =priority +1
where u1.id = u2.id
获取每个名称的最高优先级记录:
select *
from user_priority
where id in (
select min(id)
from user_priority inner join
(select name,max(urgency)as max_urg
from user_priority
group by name) as user_urgency on (user_priority.name = user_urgency.name
and user_priority.urgency = user_urgency.max_urg)
group by user_priority.name)
答案 1 :(得分:1)
好吧,我会使用此查询来选择数据库中的所有唯一名称:
SELECT DISTINCT name FROM mytable ORDER BY name;
从那里你可以得到第一个紧急的,或者如果不适用,那么第一个非紧急的那个:
SELECT
*
FROM
mytable
WHERE
name = '%'
ORDER BY
urgency DESC, output ASC
LIMIT 1
然后使用新的优先级更新该行:
UPDATE mytable SET priority = 1 WHERE id = %
显然,获得优先项目的SELECT
是微不足道的。