如何在左联接中嵌套内联接

时间:2019-04-01 20:09:38

标签: sequelize.js

想象一下,我的[人]和[电话]表之间有一个关联表[人电话]。然后运行以下查询:

续集

Person.findAll({
  include: [{
    model: PersonPhones,
    required: false,
    include: [{
      model: Phones,
      required: true
    }]
  }]
});

问题:

我想我将得到的结果等同于下面的查询1,它返回4行。但是我得到的是查询2,它仅返回2行。有没有办法强制Sequelize将INNER JOIN嵌套在LEFT JOIN下?


SQL

CREATE TABLE #Persons (id INT, name VARCHAR(50))
CREATE TABLE #Phones (id INT, number VARCHAR(20))
CREATE TABLE #PersonPhones (personId INT, phoneId INT) 

INSERT INTO #Persons VALUES (1,'Adam'), (2, 'Bob'), (3, 'Carl')
INSERT INTO #Phones VALUES (1, '555-1234'), (2, '555-2345'), (3, '555-3456')
INSERT INTO #PersonPhones VALUES (1,1), (1,3), (2, 4)

-- The following are not the same queries

-- Query 1
SELECT *
FROM #Persons p
LEFT JOIN #PersonPhones pp 
    INNER JOIN #Phones ph ON ph.id = pp.phoneID
    ON pp.personID = p.ID

-- Query 2
SELECT *
FROM #Persons p
LEFT JOIN #PersonPhones pp ON pp.personID = p.ID
INNER JOIN #Phones ph ON ph.id = pp.phoneID

2 个答案:

答案 0 :(得分:0)

尝试一下:

-- Query 1
SELECT *
FROM #Persons p
LEFT JOIN (
    select * from #PersonPhones pp 
    INNER JOIN #Phones ph ON ph.id = pp.phoneID
    ) x ON x.personID = p.ID

答案 1 :(得分:0)

与库的创建者之一交谈后,我被告知嵌套联接不是受支持的功能。 I have created an issue with their GitHub project。随时发表评论或从那里关注。