简体   繁体   中英

Distinct and Inner joins with sequelize

Can anyone tell me what is the best way to get the same result as this SQL query with Sequelize:

SELECT DISTINCT (c.id),
    c.*
FROM table1 a
INNER JOIN table2 b
    ON b.id = a."table2Id" 
INNER JOIN table3 c
    ON c.id = b."table3Id"
ORDER BY c.date DESC
LIMIT 10;

Right now, "include" give pretty much the result I need for inner join, but a "distinct" on a joined table looks way harder to get...

The goal is to join 3 tables, ordering them by the date of the third join, avoid having multiple times the same entry from the third join and finally only get the distinct entries from the third join (which will always have a "table1" relation since we started from this table to get them).

SELECT DISTINCT (b.table3Id), c.*
FROM table1 a
INNER JOIN table2 b ON b.id = a."table2Id" 
INNER JOIN table3 c ON c.id = b."table3Id"
ORDER BY c.date DESC
LIMIT 10;
Table1.findAll({ 
    attributes: [ [sequelize.fn('DISTINCT', sequelize.col('table1.table3Id')), 'c.id'] ],
    include: [ [Table2, "b"], [Table3, "c" ] ],
    order: [ [Table1.associations.Table3, 'date', 'DESC'] ],
    limit: 10
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM