簡體   English   中英

從同一表中排序MySQL選擇(左連接)

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

如何使用Sequelize從同一張表中選擇兩次? 這是MySQL代碼:

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

這是我的MySQl表

在此處輸入圖片說明

這是我的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();

終於我找到了答案。 也許對某人有用。

await ec.sequelize.sync();

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