简体   繁体   English

从同一表中排序MySQL选择(左连接)

[英]Sequelize MySQL select from the same table (left join)

How I can select from the same table twice with Sequelize? 如何使用Sequelize从同一张表中选择两次? Here is MySQL code: 这是MySQL代码:

select b.*, a.parent_id
from theSameTable as b left join theSameTable as a on b.parent_id = a.id

Here is my MySQl table 这是我的MySQl表

在此处输入图片说明

Here is my Sequelize code 这是我的Sequelize代码

const db = await ec.sequelize.define(tableDb, {
    id: {
        type: ec.Sequelize.INTEGER.UNSIGNED,
        primaryKey: true,
        autoIncrement: true
    },
    url: ec.Sequelize.STRING(511),
    url_hash: ec.Sequelize.STRING(32),
    name: ec.Sequelize.STRING(511),
    full_name: ec.Sequelize.STRING(511),
    parent_id: ec.Sequelize.INTEGER(11).UNSIGNED,
    cnt: ec.Sequelize.STRING(255),
    chk: ec.Sequelize.INTEGER(1)
}, {
    indexes: [{
        unique: true,
        fields: ['url_hash']
    }]
});

await ec.sequelize.sync();

Finally I've found an answer. 终于我找到了答案。 Maybe to someone it will be useful. 也许对某人有用。 After

await ec.sequelize.sync();

Write

db.belongsTo(db, {
    as: 'db2',
    foreignKey: 'parent_id',
    required: false
});

let rows = await db.findAll({
    where: {
        chk: 0
    },
    include: [{
        model: db,
        as: 'db2',
        attributes: ['id', 'full_name']
    }],
    raw: true,
    limit: 20
}).catch(function (err) {
    console.log(err);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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