如何在 MySQL v8 中模拟 LATERAL JOIN 来为每一行执行子查询或连接?
How can you simulate a LATERAL JOIN in MySQL v8 to execute a subquery or join for each row?
我有两个 table:
film with primary key film_id
actor with primary key actor_id
我现在想填写一个 table film_actor(film_id, actor_id)
,它将每部电影连接到 250 个随机演员。所以每部电影应该有 250 不同的 演员。
在 PostgreSQL 中,我会这样做:
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;
可在此处找到 PostgreSQL fiddle:https://dbfiddle.uk/?rdbms=postgres_10&fiddle=6dc21a3ce3404aaf3f4453e2ee4f863b。如您所见,每部电影都有不同的演员。
我在 MySQL v8 中找不到对 LATERAL JOIN
的支持。你怎么能在 MySQL v8 中做这样的构造?
一个不起作用MySQL fiddle可以在这里找到:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6c1fb7df00cf8c73cbcca77752c9ef0d正如你所看到的,每部电影都有相同的演员。
这是一个相当低效的方法:
insert into film_actor (film_id, actor_id)
select film_id, actor_id
from (select f.film_id, a.actor_id,
row_number() over (partition by film_id order by rand()) as seeqnum
from film f cross join
actor a
) fa
where seqnum <= 250;
还有一种使用递归CTE的方法,但我认为性能会更差。
LATERAL
在版本 8.0.14 中添加到 MySQL。
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.
我有两个 table:
film with primary key film_id
actor with primary key actor_id
我现在想填写一个 table film_actor(film_id, actor_id)
,它将每部电影连接到 250 个随机演员。所以每部电影应该有 250 不同的 演员。
在 PostgreSQL 中,我会这样做:
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;
可在此处找到 PostgreSQL fiddle:https://dbfiddle.uk/?rdbms=postgres_10&fiddle=6dc21a3ce3404aaf3f4453e2ee4f863b。如您所见,每部电影都有不同的演员。
我在 MySQL v8 中找不到对 LATERAL JOIN
的支持。你怎么能在 MySQL v8 中做这样的构造?
一个不起作用MySQL fiddle可以在这里找到:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6c1fb7df00cf8c73cbcca77752c9ef0d正如你所看到的,每部电影都有相同的演员。
这是一个相当低效的方法:
insert into film_actor (film_id, actor_id)
select film_id, actor_id
from (select f.film_id, a.actor_id,
row_number() over (partition by film_id order by rand()) as seeqnum
from film f cross join
actor a
) fa
where seqnum <= 250;
还有一种使用递归CTE的方法,但我认为性能会更差。
LATERAL
在版本 8.0.14 中添加到 MySQL。
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.