Drizzle | 최소 하나의 관련 자식 행이 있는 부모 행 조회
PostgreSQL
MySQL
SQLite
This guide assumes familiarity with:
이 가이드는 최소 하나의 관련 자식 행이 있는 부모 행을 조회하는 방법을 설명합니다. 아래는 스키마 정의와 해당 데이터베이스 데이터의 예제입니다:
import { integer, pgTable, serial, text } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
email: text('email').notNull(),
});
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
content: text('content').notNull(),
userId: integer('user_id').notNull().references(() => users.id),
});users.db
posts.db
+----+------------+----------------------+
| id | name | email |
+----+------------+----------------------+
| 1 | John Doe | john_doe@email.com |
+----+------------+----------------------+
| 2 | Tom Brown | tom_brown@email.com |
+----+------------+----------------------+
| 3 | Nick Smith | nick_smith@email.com |
+----+------------+----------------------+최소 하나의 관련 자식 행이 있는 부모 행을 조회하고 자식 데이터를 가져오려면 .innerJoin() 메서드를 사용할 수 있습니다:
import { eq } from 'drizzle-orm';
import { users, posts } from './schema';
const db = drizzle(...);
await db
.select({
user: users,
post: posts,
})
.from(users)
.innerJoin(posts, eq(users.id, posts.userId));
.orderBy(users.id);select users.*, posts.* from users
inner join posts on users.id = posts.user_id
order by users.id;// 결과 데이터, id가 2인 사용자는 게시글이 없어서 포함되지 않습니다
[
{
user: { id: 1, name: 'John Doe', email: 'john_doe@email.com' },
post: {
id: 1,
title: 'Post 1',
content: 'This is the text of post 1',
userId: 1
}
},
{
user: { id: 1, name: 'John Doe', email: 'john_doe@email.com' },
post: {
id: 2,
title: 'Post 2',
content: 'This is the text of post 2',
userId: 1
}
},
{
user: { id: 3, name: 'Nick Smith', email: 'nick_smith@email.com' },
post: {
id: 3,
title: 'Post 3',
content: 'This is the text of post 3',
userId: 3
}
}
]최소 하나의 관련 자식 행이 있는 부모 행만 조회하려면 다음과 같이 exists() 함수와 서브쿼리를 사용할 수 있습니다:
import { eq, exists, sql } from 'drizzle-orm';
const sq = db
.select({ id: sql`1` })
.from(posts)
.where(eq(posts.userId, users.id));
await db.select().from(users).where(exists(sq));select * from users where exists (select 1 from posts where posts.user_id = users.id);// 결과 데이터, id가 2인 사용자는 게시글이 없어서 포함되지 않습니다
[
{ id: 1, name: 'John Doe', email: 'john_doe@email.com' },
{ id: 3, name: 'Nick Smith', email: 'nick_smith@email.com' }
]