第一次在这里问一个问题所以请温柔地对待我:)
我有两张桌子:
我正在努力选择最好的"峰值"在" master"中的行的连续块(名称)中的行匹配"名称"在第二个表(单行)中。这个连续的块必须是表中最新的连续块。
所以正确的结果是:
17 | 2016-03-12 23:57:00 | 190 | Tracey
站长:
id | date time | peak | name
-------------------------------------------------
01 | 2016-03-12 23:41:00 | 201 | Tracey
02 | 2016-03-12 23:42:00 | 107 | Tracey
03 | 2016-03-12 23:43:00 | 103 | Tracey
04 | 2016-03-12 23:44:00 | 195 | Tracey
05 | 2016-03-12 23:45:00 | 134 | Tracey
06 | 2016-03-12 23:46:00 | 144 | Ian
07 | 2016-03-12 23:47:00 | 155 | Ian
08 | 2016-03-12 23:48:00 | 166 | Ian
09 | 2016-03-12 23:49:00 | 132 | Ian
10 | 2016-03-12 23:50:00 | 112 | Ian
11 | 2016-03-12 23:51:00 | 143 | Steve
12 | 2016-03-12 23:52:00 | 165 | Steve
13 | 2016-03-12 23:53:00 | 122 | Steve
14 | 2016-03-12 23:54:00 | 123 | Steve
15 | 2016-03-12 23:55:00 | 132 | Steve
16 | 2016-03-12 23:56:00 | 143 | Steve
17 | 2016-03-12 23:57:00 | 190 | Tracey ----
18 | 2016-03-12 23:58:00 | 165 | Tracey |
19 | 2016-03-12 23:59:00 | 154 | Tracey | latest
20 | 2016-03-13 00:00:00 | 131 | Tracey | contiguous
21 | 2016-03-13 00:01:00 | 167 | Tracey | block
22 | 2016-03-13 00:02:00 | 178 | Tracey ----
电流:
id | date time | peak | name
---------------------------------------------
01 | 2016-03-13 00:02:00 | 178 | Tracey
更新@EhsanT
我试过了:
SET @name = 'Tracey';
SELECT * FROM `Master`
WHERE `name` = @name
AND `id` > (
SELECT max(`id`)
FROM `Master`
WHERE `name` != @name
AND `id` < (
SELECT max(`id`)
FROM `Master`
WHERE `name` = @name
)
)
ORDER BY peak DESC
LIMIT 1
答案 0 :(得分:3)
此答案的最佳做法是使用procedures
。
由于我不是编写Master
的专家,您可以使用下面的代码,但是在运行此代码之前应该进行一些验证,例如检查传递给代码的名称是否存在于Master
表,或者如果表中此名称之前还有其他名称,则此名称仅在Master
表中。
假设select max(`peak`)
from `Master`
where `name` = 'Tracey'
and `id` > (
select max(`id`)
from `Master`
where `name` != 'Tracey'
and `id` < (
select max(`id`)
from `Master`
where `name` = 'Tracey'
)
)
表中有大量记录且上述两个条件都是正确的,那么这段代码将为您完成这项工作:
peak
我也确定你知道这一点,但是如果你想要整个记录数据,你只需要按select *
from `Master`
where `name` = 'Tracey'
and `id` > (
select max(`id`)
from `Master`
where `name` != 'Tracey'
and `id` < (
select max(`id`)
from `Master`
where `name` = 'Tracey'
)
)
order by peak desc
limit 1
降序排列记录并将它们限制为1.
所以最后的查询将是这样的:
{{1}}
答案 1 :(得分:0)
Select * from master where peak = (Select MAX(peak) from master where name = (Select name from current))