Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you simulate a LATERAL JOIN in MySQL v8 to execute a subquery or join for each row?

I have two tables:

film  with primary key film_id
actor with primary key actor_id

I now want to fill a table film_actor(film_id, actor_id) which connects each film to 250 random actors. So each film should have 250 different actors.

In PostgreSQL, I would do:

insert into film_actor(film_id, actor_id)
select film_id, actor_id
from   film
cross join lateral
(
    select actor_id
    from   actor
    where  film_id is not null -- to force lateral behavior
    order  by random()
    limit  250
) as actor;

A PostgreSQL fiddle can be found here: https://dbfiddle.uk/?rdbms=postgres_10&fiddle=6dc21a3ce3404aaf3f4453e2ee4f863b. As you can see, each film has different actors.

I cannot find support for LATERAL JOINs in MySQL v8. How can you do such constructs in MySQL v8?

A not working MySQL fiddle can be found here: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6c1fb7df00cf8c73cbcca77752c9ef0d As you can see, each film has the same actors.

like image 386
Jelly Orns Avatar asked Jan 03 '23 08:01

Jelly Orns


1 Answers

LATERAL was added to MySQL in ver 8.0.14.

https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-14.html#mysqld-8-0-14-sql-syntax https://dev.mysql.com/doc/refman/8.0/en/lateral-derived-tables.html

A derived table cannot normally refer to (depend on) columns of preceding tables in the same FROM clause. As of MySQL 8.0.14, a derived table may be defined as a lateral derived table to specify that such references are permitted.

like image 82
Adam Wulkiewicz Avatar answered Jan 05 '23 16:01

Adam Wulkiewicz