简体   繁体   English

如何在MySQL v8中模拟LATERAL JOIN以执行每行的子查询或连接?

[英]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. 我现在想填写一个表film_actor(film_id, actor_id) ,它将每部电影连接到250个随机演员。 So each film should have 250 different actors. 所以每部电影应该有250个不同的演员。

In PostgreSQL, I would do: 在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;

A PostgreSQL fiddle can be found here: https://dbfiddle.uk/?rdbms=postgres_10&fiddle=6dc21a3ce3404aaf3f4453e2ee4f863b . PostgreSQL小提琴可以在这里找到: https//dbfiddle.uk/?rbms = postgres_10&_fiddle = 6dc21a3ce3404aaf3f4453e2ee4f863b As you can see, each film has different actors. 正如你所看到的,每部电影都有不同的演员。

I cannot find support for LATERAL JOIN s in MySQL v8. 我在MySQL v8中找不到对LATERAL JOIN的支持。 How can you do such constructs in MySQL v8? 你怎么能在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. 一个不工作的MySQL小提琴可以在这里找到: https//dbfiddle.uk/? rbms = mysql_8.0&tele = 6c1fb7df00cf8c73cbcca77752c9ef0d正如你所看到的,每部电影都有相同的演员。

Here is a rather inefficient method of doing this: 这是一个相当低效的方法:

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;

There is also a method using recursive CTEs, but I think the performance would be even worse. 还有一种使用递归CTE的方法,但我认为性能会更差。

LATERAL was added to MySQL in ver 8.0.14. 在版本8.0.14中将LATERAL添加到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 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. 派生表通常不能引用同一FROM子句中前面表的(依赖于)列。 As of MySQL 8.0.14, a derived table may be defined as a lateral derived table to specify that such references are permitted. 从MySQL 8.0.14开始,可以将派生表定义为横向派生表,以指定允许此类引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM