Join in subquery failing on MySQL 5.7

huangapple go评论57阅读模式
英文:

Join in subquery failing on MySQL 5.7

问题

I'm writing a data migration in SQL for an app that has to support multiple possible databases, including MySQL 5.7. Here is the code that I currently have:

UPDATE sandboxes s
SET permission_id = (
  SELECT p.id
  FROM permissions p
  JOIN tables t ON t.id = s.table_id
  WHERE
    p.object LIKE CONCAT('/db/', t.db_id, '/schema/', t.schema, '/table/', s.table_id, '/query/segmented/')
    AND p.group_id = s.group_id
  LIMIT 1
)
WHERE permission_id IS NULL;

This fails on MySQL 5.7 with the error Unknown column 's.table_id' in 'on clause'. I'm assuming the ON clause is more strict in 5.7 than in later versions since it works in other versions of MySQL as well as in Postgres. Is there any way to get around this limitation? Or a way I can rewrite the query? I'm not great with SQL, so any help is appreciated.

英文:

I'm writing a data migration in SQL for an app that has to support multiple possible databases, including MySQL 5.7. Here is the code that I currently have:

UPDATE sandboxes s
SET permission_id = (
  SELECT p.id
  FROM permissions p
  JOIN tables t ON t.id = s.table_id
  WHERE
    p.object LIKE CONCAT('/db/', t.db_id, '/schema/', t.schema, '/table/', s.table_id, '/query/segmented/')
    AND p.group_id = s.group_id
  LIMIT 1
)
WHERE permission_id IS NULL;

This fails on MySQL 5.7 with the error Unknown column 's.table_id' in 'on clause'. I'm assuming the ON clause is more strict in 5.7 than in later versions since it works in other versions of MySQL as well as in Postgres. Is there any way to get around this limitation? Or a way I can rewrite the query? I'm not great with SQL so any help is appreciated.

答案1

得分: 1

不清楚为什么会出现错误,但您可以通过在UPDATE查询中使用JOIN而不是子查询来解决它。

UPDATE sandboxes s
JOIN permissions AS p ON p.group_id = s.group_id
JOIN tables AS t ON t.table_id = s.table_id AND p.object = CONCAT('/db/', t.db_id, '/schema/', t.schema, '/table/', s.table_id, '/query/segmented/')
SET s.permission_id = p.id
英文:

It's not clear why you're getting the error, but you can solve it by using a JOIN in the UPDATE query rather than a subquery.

UPDATE sandboxes s
JOIN permissions AS p on p.group_id = s.group_id
JOIN tables AS t ON t.table_id = s.table_id AND p.object = CONCAT('/db/', t.db_id, '/schema/', t.schema, '/table/', s.table_id, '/query/segmented/')
SET s.permission_id = p.id

huangapple
  • 本文由 发表于 2023年6月13日 06:43:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定