你能定义“字面"吗?SQL中的表?

2022-01-23 00:00:00 sql subquery mysql temp-tables

是否有任何 SQL 子查询语法可以让您从字面上定义一个临时表?

Is there any SQL subquery syntax that lets you define, literally, a temporary table?

例如,类似

SELECT
  MAX(count) AS max,
  COUNT(*) AS count
FROM
  (
    (1 AS id, 7 AS count),
    (2, 6),
    (3, 13),
    (4, 12),
    (5, 9)
  ) AS mytable
  INNER JOIN someothertable ON someothertable.id=mytable.id

这样可以省去两到三个查询:创建临时表,将数据放入其中,然后在连接中使用它.

This would save having to do two or three queries: creating temporary table, putting data in it, then using it in a join.

我正在使用 MySQL,但对其他可以做类似事情的数据库感兴趣.

I am using MySQL but would be interested in other databases that could do something like that.

推荐答案

我想你可以用几个 SELECTs 结合 UNIONs 来做一个子查询.

I suppose you could do a subquery with several SELECTs combined with UNIONs.

SELECT a, b, c, d
FROM (
    SELECT 1 AS a, 2 AS b, 3 AS c, 4 AS d
    UNION ALL 
    SELECT 5 , 6, 7, 8
) AS temp;

相关文章