gpt4 book ai didi

mysql max(时间戳)查询nodejs

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

我希望使用 maxtime 时间戳值获取数据库中最新的记录。下面列出了数据库布局

database layout

这是我的代码,包括我正在运行以检索所需行的查询

var mysql = require("mysql");

var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'database',
database : 'airplanemap'
});

connection.connect(function (err) {
if(err) {
console.error('error connecting' + err.stack);
return;
}

console.log('connected as id' + connection.threadId);

connection.query('SELECT name, baggageno, destination, max(ts) FROM map', function (err, results, fields) {

if(err) {
console.error(err.stack);
return;
}

if(results.length > 0) {
var myresult = results[0];
console.log('results ' + myresult['name'] + ' ' + myresult['baggageno'] + ' ' + myresult['destination'] + ' ' + myresult['max(ts)']);
}
else
{
console.log('no results');
}
})
});

我收到的结果是

简 2 纽约 2015 年 3 月 14 日星期六 02:25:03 GMT-0400

由此返回最高时间戳,但名称、行李号和目的地的列值错误

应该是

约翰 5 多伦多 2015 年 3 月 14 日星期六 02:25:03 GMT-0400

我做错了什么?

编辑:我期望结果数组中的一行值是表中具有最新时间戳的行。

最佳答案

当前您的查询返回 4 行:

[
{ name: 'john', baggageno: 5, destination: 'toronto', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' },
{ name: 'jill', baggageno: 1, destination: 'karachi', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' },
{ name: 'jane', baggageno: 2, destination: 'new york', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' },
{ name: 'jim', baggageno: 5, destination: 'glasgow', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' },
]

并且您从结果集中选择了第一行,这就是您看到所看到内容的原因(尽管行的顺序取决于服务器,因为您没有请求特定的顺序) )。

如果您尝试查找具有最新 ts 值的记录,则需要添加某种过滤器。例如,使用联接可能类似​​于:

SELECT map.*
FROM map
LEFT JOIN map map2 ON map.name = map2.name
AND map.baggageno = map2.baggageno
AND map.destination = map2.destination
AND map.ts < map2.ts
WHERE map2.name IS NULL

如果您想这样做,除了使用内部联接之外,您还可以执行类似的操作。

关于mysql max(时间戳)查询nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29046198/

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