假设我正在构建一个有 4 个表的地址簿:user
, contact
, friend
, and stranger
.
contact
是链接表连接user
与两个friend
and stranger
表。它的结构如下:
╔════╦═════════╦═══════════╦═════════════╗
║ id ║ user_id ║ friend_id ║ stranger_id ║
╠════╬═════════╬═══════════╬═════════════╣
║ 1 ║ 1 ║ 5 ║ NULL ║
╠════╬═════════╬═══════════╬═════════════╣
║ 2 ║ 1 ║ NULL ║ 65 ║
╠════╬═════════╬═══════════╬═════════════╣
║ 3 ║ 1 ║ 87 ║ NULL ║
╚════╩═════════╩═══════════╩═════════════╝
我想创建一个如下所示的视图:
╔════╦═════════╦═══════════╦═════════════╦══════════════╗
║ id ║ user_id ║ friend_id ║ stranger_id ║ contact_name ║
╠════╬═════════╬═══════════╬═════════════╬══════════════╣
║ 1 ║ 1 ║ 5 ║ NULL ║ Barry ║
╠════╬═════════╬═══════════╬═════════════╬══════════════╣
║ 2 ║ 1 ║ NULL ║ 65 ║ Gary ║
╠════╬═════════╬═══════════╬═════════════╬══════════════╣
║ 3 ║ 1 ║ 87 ║ NULL ║ Larry ║
╚════╩═════════╩═══════════╩═════════════╩══════════════╝
也就是说,我想要一个可以使用查询的视图user_id
并获取该用户的所有联系人的列表with the name
两者共有的列friend
and stranger
tables.
理想情况下,我想使用 TypeORM 来实现这一点,但只要知道正确的 SQL 也会有所帮助。
尝试定义一个视图实体 https://typeorm.io/#/view-entities它在之间执行左连接contacts
, friends
and stranger
桌子。然后结果行将被映射到ContactWithName
对象,从而一个新的领域contact_name
添加了其中concats https://www.postgresqltutorial.com/postgresql-concat-function/ the name
的栏目friends
and stranger
table (NULL
字段将被忽略)。
@ViewEntity({
expression: (connection: Connection) => connection.createQueryBuilder(Contact, "contact")
.select ('contact.id', 'id')
.addSelect('contact.user_id', 'user_id')
.addSelect('contact.friend_id', 'friend_id')
.addSelect('contact.stranger_id', 'stranger_id')
.addSelect('CONCAT(friend.name, stranger.name)', 'contact_name')
.leftJoin (Friend, "friend") // friend table
.leftJoin (Stranger, "stranger") // stranger table
})
export class ContactWithName {
@ViewColumn()
id: number;
@ViewColumn()
user_id: number;
@ViewColumn()
friend_id: number;
@ViewColumn()
stranger_id: number;
@ViewColumn()
contact_name: string;
}
然后,您可以照常查询结果集:getRepository(ContactWithName).find(...)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)