node-sql-query构建复杂查询

时间:2016-02-04 06:54:53

标签: mysql node.js subquery sails.js waterline

我将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`

它有效。

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

我刚刚找到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();

然后使用水线评估查询:

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

答案 1 :(得分:0)

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

Model.query(query, params, callback);