【问题标题】:Mysql support this kind of "with" sql?mysql支持这种“with”sql吗?
【发布时间】:2020-02-18 02:21:08
【问题描述】:

在postgres中,我经常使用这种sql。

with list (id, name) as ( 
    values 
    (1004007, 'aaa'), 
    (1002147, 'bbb'), 
    (1004493, 'ccc'), 
    (1007978, 'ddd'), 
    (1005218, 'eee'), 
    (1005507, 'fff') 
)
select * from list;

Mysql 支持那种 sql 吗?

【问题讨论】:

  • 我怀疑不是 - 但请随时try it
  • VALUES 语句是 MySQL 8.0.19 中的新语句(早期版本不支持它),语法与您显示的略有不同。我还没有尝试将它与 CTE 结合使用。

标签: mysql sql postgresql


【解决方案1】:

你可以使用select:

with list (id, name) as ( 
      select 1004007, 'aaa' union all 
      select 1002147, 'bbb' union all 
      select 1004493, 'ccc' union all
      select 1007978, 'ddd' union all
      select 1005218, 'eee' union all
      select 1005507, 'fff'
     )
select l.*
from list l;

Here 是一个 dbfiddle。注意:这也适用于 Postgres。

MySQL 8.0 之前的版本不支持with。您可以创建派生表:

select list.*
from (select 1004007, 'aaa' union all 
      select 1002147, 'bbb' union all 
      select 1004493, 'ccc' union all
      select 1007978, 'ddd' union all
      select 1005218, 'eee' union all
      select 1005507, 'fff'
     ) list;

这可以像表引用一样使用。

【讨论】:

    【解决方案2】:

    mysql 8.0 以后,我们可以像下面这样使用它

    with 
    list (a, b, c) as (VALUES 
    ROW('1',-2,3), 
    ROW('5',7,9), 
    ROW('4',6,8)
    )
    select * from list;
    

    【讨论】:

      猜你喜欢
      • 2011-05-03
      • 1970-01-01
      • 2015-12-05
      • 2010-09-21
      • 2011-04-07
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      相关资源
      最近更新 更多