我的数据库有一个用户表,其中包含 first_name
和 last_name
列,其中任何一个都可能为空。
我还有一个 UI 仪表板,它显示一个带有 full_name
列的表,该列是两个字段的串联,该列是可排序的。
我正在使用带有 mysql 数据库的 sequelize 来获取用户,我如何通过 full_name
进行排序(并修剪连接字段的空格)
最佳答案
SQL 解决方案
您可以按多列排序
SELECT * FROM user ORDER BY last_name ASC, first_name ASC
或者您首先连接两个字段并按
full_name
排序(但请记住这可能很慢)SELECT *, TRIM(CONCAT(first_name,' ', last_name)) full_name FROM user ORDER BY full_name ASC
Sequelize 解决方案
const { Sequelize, DataTypes } = require('sequelize')
const User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
first_name: {
type: DataTypes.STRING(100)
},
last_name: {
type: DataTypes.STRING(100)
},
//virtual attribute for concatenation of first_name and last_name
full_name: {
type: DataTypes.VIRTUAL,
get() {
const firstName = this.getDataValue('first_name');
const lastName = this.getDataValue('last_name');
return [firstName, lastName].join(' ').trim();
}
},
});
User.findAll({
/** Order by multiples columns **/
//order: [['first_name', 'DESC'], ['last_name', 'ASC']],
/** Order by the two fields concatenated and trimed */
order: Sequelize.literal("trim(concat(first_name,' ', last_name)) ASC")
}).then(users => {
users.forEach(user=> {
console.log(user.get());
})
})
关于express - 通过两个字段的连接对mysql顺序进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61727879/