nodejs复杂的mysql别名查询?

mznpcxlj  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(319)

下面是我在nodejs中使用的一个简单的mysql查询,它工作得很好;

Audiopost.getAll = result => {
  sql.query("SELECT * FROM audioposts", (err, res) => {
    if (err) {
      console.log("error: ", err);
      result(null, err);
      return;
    }

    console.log("audioposts: ", res);
    result(null, res);
  });
};

然而,当我试图用更复杂的查询替换“select*fromAudioPosts”语句时,我得到;

SyntaxError: Invalid or unexpected token.

下面是来自php页面的更复杂的查询;

SELECT
    ap.audioname, 
    ap.userid, 
    ap.audioid, 
    ap.title, 
    ap.likes,
    ap.opid,
    u.gavatar, 
    u.name, 
    u.email,
    u.bio,
    (
        SELECT GROUP_CONCAT(t.tagname)
        FROM entitytag et
        LEFT JOIN tags t on t.tagid = et.tagid
        WHERE et.audioid = ap.audioid
    ) tagname,
    (
      SELECT count(*) FROM audioposts op WHERE op.opid = ap.audioid
    ) as replycount
        FROM audioposts ap 
        LEFT JOIN users u ON u.id = ap.userid
      WHERE ap.opid = '0'

我可以在nodejs的sql代码中使用别名吗?我做错什么了?如何执行此查询?

0qx6xfy6

0qx6xfy61#

javascript中的单引号和双引号字符串中不允许使用换行符。你要么用 \n 或者使用反引号而不是引号来定义字符串。backticks(`)创建一个允许换行的模板文本。

let query = `
SELECT
    ap.audioname, 
    ap.userid, 
    ap.audioid, 
    ap.title, 
    ap.likes,
    ap.opid,
    u.gavatar, 
    u.name, 
    u.email,
    u.bio,
    (
        SELECT GROUP_CONCAT(t.tagname)
        FROM entitytag et
        LEFT JOIN tags t on t.tagid = et.tagid
        WHERE et.audioid = ap.audioid
    ) tagname,
    (
      SELECT count(*) FROM audioposts op WHERE op.opid = ap.audioid
    ) as replycount
        FROM audioposts ap 
        LEFT JOIN users u ON u.id = ap.userid
      WHERE ap.opid = '0'
`;

sql.query(query, (err, res) => {/* ... */})

相关问题