Sequelize PG:选择加入,顺序,限制

时间:2017-02-15 12:06:02

标签: node.js postgresql sequelize.js

我在Postgres上使用Sequelize 3.30.0。这是我想要执行的查询:

SELECT works.title, artists.name, artists.relevance
FROM works
JOIN artist_works ON works.work_id = artist_works.work_id
JOIN artists ON artists.artist_id = artist_works.artist_id
WHERE artists.label LIKE '%mozart%'
ORDER BY artists.relevance DESC
LIMIT 50

如果我直接在数据库上执行它,它非常简单并且就像一个魅力。但是,试图用Sequelize做同样的事情似乎不起作用(没有结果)。这就是findAll选项的样子:

Work.findAll({
   attributes : ['title'],
   include : [{
      attributes : [ 'name' ],
      model : Artist,
      where : { label : { $like : '%mozart%' } },
   }],
  limit : 50
})

Sequelize生成的查询非常错综复杂:

SELECT "works".*, "artists"."artist_id" AS "artists.artistId", "artists"."name" AS "artists.name", "artists.artist_works"."artist_work_id" AS "artists.artist_works.artistWorkId", "artists.artist_works"."artist_id" AS "artists.artist_works.artistId", "artists.artist_works"."work_id" AS "artists.artist_works.workId", "artists.artist_works"."type" AS "artists.artist_works.type", "artists.artist_works"."artist_id" AS "artists.artist_works.artist_id", "artists.artist_works"."work_id" AS "artists.artist_works.work_id" 
FROM (
    SELECT "works"."work_id" AS "workId", "works"."title" 
    FROM "works" AS "works" 
    WHERE ( 
        SELECT "artist_works"."artist_work_id" 
        FROM "artist_works" AS "artist_works" 
        INNER JOIN "artists" AS "artist" ON "artist_works"."artist_id" = "artist"."artist_id" 
        WHERE ("works"."work_id" = "artist_works"."work_id") LIMIT 1 
    ) IS NOT NULL 
    LIMIT 50) AS "works" 
INNER JOIN (
   "artist_works" AS "artists.artist_works" 
      INNER JOIN "artists" AS "artists" ON "artists"."artist_id" = "artists.artist_works"."artist_id"
      ) ON "works"."workId" = "artists.artist_works"."work_id" AND "artists"."label" LIKE '%-mozart-%';

请注意,如果未设置限制,则查询有效。 此外,当我尝试添加order选项时,查询会冻结。 想法?

1 个答案:

答案 0 :(得分:1)

存在相关问题Sequelize with NodeJS can't join tables with limit,解决方案似乎是在subQuery: false方法中向options对象添加findAll。它会阻止创建与您相关的子查询。

我创建了相同的关联并添加了subQuery: false,并且未生成子查询,以及LIMITORDER似乎也有效。但是,如果您真的想使用selectQuery选项,我建议您从node_modules/sequelize/lib/dialects/abstract/query-generator.js查看subQuery的源代码,因为文档中没有提到它,所以我不保证它会起作用