sql - 使用knex对3张表进行join操作

标签 sql postgresql join knex.js

我有一个对 2 个表执行 innerJoin 操作的 SQL 查询。

表 1:用户

enter image description here

表 2:local_auth

enter image description here

查询根据user_id键返回所有匹配的行

async getUser(id) {
    return camelizeKeys(
        await knex
        .select(
            'u.id',
            'u.first_name',
            'u.last_name',
            'u.username',
            'u.image_url',
            'u.is_admin',
            'u.phone',
            'u.info',
            'la.email'
        )
        .from('user AS u')
        .leftJoin('local_auth AS la', 'la.user_id', 'u.id')
        .where('u.id', '=', id)
        .first()
    );
}

现在,我要做的是修改上面的查询,使其对 3 个表执行连接操作。

表 3:customer_user

enter image description here

还有一个名为customer_user 的表,它的外键之一是user_id。如何根据 user_idcustomer_user 表中检索某些字段。我想执行这样的操作(但是由于使用 knex 执行多个连接的方式不正确,以下当然不会起作用)

async getUser(id) {
    return camelizeKeys(
        await knex
        .select(
            'u.id',
            'u.first_name',
            'u.last_name',
            'u.username',
            'u.image_url',
            'u.is_admin',
            'u.phone',
            'u.info',
            'la.email',
            'cu.customer_id',
            'cu.department_id'
        )
        .from('user AS u')
        .leftJoin('local_auth AS la', 'la.user_id', 'u.id')
        .leftJoin('customer_user AS cu', 'cu.user_id', 'u.id')
        .where('u.id', '=', id)
        .first()
    );
}

注意:由于在 SO 上添加 table 标记的限制,我附上了屏幕截图。

最佳答案

实际上,查询工作得很好。由于语法错误,我无法执行它

async getUser(id) {
    return camelizeKeys(
        await knex
        .select(
            'u.id',
            'u.first_name',
            'u.last_name',
            'u.username',
            'u.image_url',
            'u.is_admin',
            'u.phone',
            'u.info',
            'la.email',
            'cu.customer_id',
            'cu.department_id'
        )
        .from('user AS u')
        .leftJoin('local_auth AS la', 'la.user_id', 'u.id')
        .leftJoin('customer_user AS cu', 'cu.user_id', 'u.id')
        .where('u.id', '=', id)
        .first()
    );
}

关于sql - 使用knex对3张表进行join操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46469638/

相关文章:

SQL:使用存储在 table_1 中的值根据 table_2 中列出的变量填充 table_2 中的列

sql - SQL Server 的良好实践 : nvarchar(max) performance

SQL 将多列拆分为多行

sql - 是否有一个选择性子句可以直接在 PostgreSQL 中注入(inject)选择性,类似于 IBM DB2

postgresql - 如何获得 POSTGRESQL 的数据库设计来创建 ER 图?

mysql - 使用连接和条件限制 sql 查询结果

mysql - 使用连接表、分组依据和位置的 SQL 查询

c# - 从字符串中删除所有特殊字符

mysql - 从表中选择两次 PHP SQL

mysql - JOIN(表名)