node-sql-query 构建复杂查询

node-sql-query build complex query

我使用 Node.js 和 sails.js

我正在尝试构建一个查询,其中包含一个子查询,如下所示:

SELECT 
    `id`, `col1`, `col2`, `col3`,
    (SELECT COUNT(*) FROM `tablename` 
        WHERE (`col1` = 'someValue') AND (`col2` = `t`.`col2`)) AS `total` 
FROM `tablename` `t` 
WHERE `col1` = 'value2' AND `col3` = 'value3' 
ORDER BY `total` ASC

我知道我可以在我的模型中写:

//./api/models/tablename.js
module.exports = {
    ...
    functionName() {
        this.query(aboveSQLQuery)
            .then(found => {
                doSomething();
            })
            .catch(err => {
                handleError(err);
            });
    }
}

但我不想使用它,所以我找到了 node-sql-query 模块,这样我就可以像这样构建查询:

let
    sql = require('sql-query'),
    sqlQuery = sql.Query(),
    sqlSelect = sqlQuery.select(),
    subQuery = sqlSelect
        .from('tablename')
        .where({col1: "someValue"}, {__sql: [['col2 = t.col2']]})
        .count()
        .build(),

    /* subQuery = "SELECT COUNT(*) FROM `tablename` 
                   WHERE (`col1` = 'someValue') AND (`col2` = `t`.`col2`)"
    */

    masterQuery = sqlSelect
        .from('tablename')
        .select(['id', 'col1', 'col2', 'col3', {a: "total", sql: subQuery}])
        .where({col1: "value2", col3: "value3"})
        .order('total', 'A')
        .build();

    /* masterQuery = "SELECT `id`, `col1`, `col2`, `col3`, 
                          (SELECT COUNT(*) FROM `tablename` 
                          WHERE (`col1` = 'someValue') AND (`col2` = `t`.`col2`)) 
                          AS `total` 
                      FROM `tablename` 
                      WHERE `col1` = 'value2' AND `col3` = 'value3' 
                      ORDER BY `total` ASC"
    */

masterQuery 没有按预期工作,但是如果我将第二个 FROM

更改为
FROM `tablename`

FROM `tablename` `t`

有效。

任何帮助将不胜感激

我刚找到 knex,并设法完成了这个:

let
    knex = require('knex')({
        client: "mysql"
    }),
    subQuery, masterQuery;

subQuery = knex('tablename')
    .count()
    .where({col1: "someValue"})
    .andWhereRaw('`col2` = `t`.`col2`')
    .select()
    .from('tablename')
    .as('total');

masterQuery = knex('tablename')
    .select(['id', 'col1', 'col2', 'col3', subQuery])
    .from(knex.raw('`tablename` `t`'))
    .where({col1: "value2", location: "value3"})
    .orderBy('total', 'asc')
    .limit(1)
    .toString();

然后使用 waterline 评估查询:

this.query(masterQuery, (err, found) => {
    doSomething();
});

Waterline 使用 node-mysql package,因此您可以为您的模型执行任何纯 sql 查询,例如:

Model.query(query, params, callback);