【问题标题】:Get the most recent date from the mysql using knex使用 knex 从 mysql 获取最新日期
【发布时间】:2020-06-12 01:33:50
【问题描述】:
"SELECT * FROM stocks WHERE timestamp IN (SELECT max(timestamp) FROM stocks) AND industry = 'Health Care'"

以上是我之前使用的查询,但现在我需要将其更改为 knex 形式。我对其他人很好,但不知道如何将 where 条件更改为 knex 形式。

每只股票都有数千个日期,我只想从中获得最多的日期。有很多简单查询的示例,但没有用于 knex 形式的示例。

【问题讨论】:

    标签: mysql node.js express knex.js


    【解决方案1】:

    你知道如何重写这个吗?

    SELECT s.* 
      FROM stocks s
      JOIN (SELECT max(timestamp) ts FROM stocks) x 
        ON x.ts = s.timestamp
     WHERE s.industry = 'Health Care'
    

    【讨论】:

    • 不确定...它和我的工作一样吗?
    • 是的,而且(如果索引适当的话)效率更高
    • .join(db.select(max(timestamp)).from stock) .on()...不确定它是如何工作的
    【解决方案2】:
    router.get("/api/stock", function (req, res, next) {
      req.db
        .from("stocks")
        .select("*")
        .where("name", "=","Agilent Technologies Inc" )
        .then((rows) => {
          res.json({ Error: false, Message: "Success", City: rows })
        })
        .catch((err) => {
          console.log(err)
          res.json({ Error: false, Message: "Error in MySQL query" })
        })
    })
    

    这是我到目前为止想出的,打印出来的行数为 100 行。由于我没有提出任何条件......但不知道从哪里开始

    【讨论】:

      【解决方案3】:
      SELECT s.* 
        FROM stocks s
        JOIN (SELECT max(timestamp) ts FROM stocks) x 
          ON x.ts = s.timestamp
       WHERE s.industry = 'Health Care'
      

      knex({s: 'stocks'})
        .select('s.*')
        .join(
          knex('stocks').select(knex.raw('max(??) as ts', ['timestamp'])).as('x'),
          'x.ts', 
          '=', 
          's.timestamp'
        ).where('s.industry', 'Health Care');
      

      runkit:https://runkit.com/embed/s0iibv1byrd0

      【讨论】:

        猜你喜欢
        • 2012-01-18
        • 1970-01-01
        • 1970-01-01
        • 2020-08-16
        • 2014-03-10
        • 2012-10-13
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多