Examples of queries that use joins.
Simple inner join
Schema
import { Generated } from ' kysely '
created_at : Generated < Date >
Querying
. innerJoin ( ' pet ' , ' pet.owner_id ' , ' person.id ' )
// `select` needs to come after the call to `innerJoin` so
// that you can select from the joined table.
. select ([ ' person.id ' , ' pet.name as pet_name ' ])
Result
" pet " . " name " AS " pet_name "
INNER JOIN " pet " ON " pet " . " owner_id " = " person " . " id "
` pet ` . ` name ` AS ` pet_name `
INNER JOIN ` pet ` ON ` pet ` . ` owner_id ` = ` person ` . ` id `
" pet " . " name " AS " pet_name "
INNER JOIN " pet " ON " pet " . " owner_id " = " person " . " id "
Aliased inner join
Schema
import { Generated } from ' kysely '
created_at : Generated < Date >
Querying
await db . selectFrom ( ' person ' )
. innerJoin ( ' pet as p ' , ' p.owner_id ' , ' person.id ' )
. where ( ' p.name ' , ' = ' , ' Doggo ' )
Result
INNER JOIN " pet " AS " p " ON " p " . " owner_id " = " person " . " id "
INNER JOIN ` pet ` AS ` p ` ON ` p ` . ` owner_id ` = ` person ` . ` id `
INNER JOIN " pet " AS " p " ON " p " . " owner_id " = " person " . " id "
Complex join
You can provide a function as the second argument to get a join builder for creating more complex joins. The join builder has a bunch of on*
methods for building the on
clause of the join. There’s basically an equivalent for every where
method (on
, onRef
etc.).
You can do all the same things with the on
method that you can with the corresponding where
method (like OR expressions for example ). See the where
method documentation for more examples.
Schema
import { Generated } from ' kysely '
created_at : Generated < Date >
Querying
await db . selectFrom ( ' person ' )
. onRef ( ' pet.owner_id ' , ' = ' , ' person.id ' )
. on ( ' pet.name ' , ' = ' , ' Doggo ' )
. on ( ( eb ) => eb . or ([ eb ( " person.age " , " > " , 18 ), eb ( " person.age " , " < " , 100 )]))
Result
INNER JOIN " pet " ON " pet " . " owner_id " = " person " . " id "
INNER JOIN ` pet ` ON ` pet ` . ` owner_id ` = ` person ` . ` id `
INNER JOIN " pet " ON " pet " . " owner_id " = " person " . " id "
Subquery join
Schema
import { Generated } from ' kysely '
created_at : Generated < Date >
Querying
const result = await db . selectFrom ( ' person ' )
. select ([ ' owner_id as owner ' , ' name ' ])
. where ( ' name ' , ' = ' , ' Doggo ' )
. onRef ( ' doggos.owner ' , ' = ' , ' person.id ' ),
Result
) AS " doggos " ON " doggos " . " owner " = " person " . " id "
) AS ` doggos ` ON ` doggos ` . ` owner ` = ` person ` . ` id `
) AS " doggos " ON " doggos " . " owner " = " person " . " id "
MORE EXAMPLES
The API documentation is packed with examples. The API docs are hosted here but you can access the same documentation by hovering over functions/methods/classes in your IDE. The examples are always just one hover away!
For example, check out these sections:
innerJoin method leftJoin method rightJoin method fullJoin method