gpt4 book ai didi

mysql - 为mysql中每条返回记录选择最大值

转载 作者:行者123 更新时间:2023-11-29 18:02:12 24 4
gpt4 key购买 nike

我的表格看起来像这样

表1:

relid  BID 
1 1
1 2
1 3

表2:

id BID priority info 
1 1 0 Json string
2 1 1 **
3 1 2 ****
4 2 0 ***
5 2 1 ****

6 3 0 ****

问题是我想使用table1使用inner jointable2中选择具有最高优先级的所有BID,这意味着我想要得到这个结果

id  BID  Priority info 
3 1 2 Json String info
5 2 1 ***
6 3 0 ***

我已经使用了这个查询,它工作正常,但对于大量记录,它工作得太慢了!在 MySQL 中,获取时间可能长达 70 秒,这对我的服务器来说是一场灾难!

select * from table1 inner join table2 on table1.BID = table2.BID where table1.relid = 1 and table2.priority = (select max(priority) as m from table2 where table1.BID = table2.BID)

任何人都有其他可能会带来更好性能的建议!

最佳答案

考虑以下因素:

SELECT y.id 
, y.bid
, y.priority
, y.info
FROM table1 x
JOIN table2 y
ON x.BID = y.BID
JOIN (SELECT bid, MAX(priority) max_priority from table2 GROUP BY bid) z
ON z.bid = y.bid
AND z.max_priority = y.priority
WHERE x.relid = 1;

为了进一步改进,我们确实需要查看所有相关表的正确 CREATE TABLE 语句以及 EXPLAIN 的结果

关于mysql - 为mysql中每条返回记录选择最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48248501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com