将mysql子查询存储在变量中

时间:2012-03-20 10:57:39

标签: mysql

是否可以以某种方式存储mysql子查询,如果它将再次用作子查询?据推测,这将产生更清晰的代码以及节省解析开销。

例如,在以下外部联接中

SELECT * FROM t1
LEFT JOIN (SELECT * FROM t2 WHERE t2.foo=='bar') ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN (SELECT * FROM t2 WHERE t2.foo=='bar') ON t1.id = t2.id

不重复(SELECT * FROM t2 WHERE t2.foo=='bar')会很好。

2 个答案:

答案 0 :(得分:4)

不,你不能。如果MySQL有CTE(公用表表达式),你可以使用它:

WITH tmp AS
  (SELECT * FROM t2 WHERE t2.foo = 'bar')
SELECT * FROM t1
  LEFT JOIN tmp ON t1.id = tmp.id
UNION
SELECT * FROM t1
  RIGHT JOIN tmp ON t1.id = tmp.id

如果MySQL有FULL JOIN(唉,它没有!),你可以使用它:

SELECT * FROM t1
  FULL JOIN (SELECT * FROM t2 WHERE t2.foo = 'bar') tmp
    ON t1.id = tmp.id

答案 1 :(得分:3)

当然这样做

SET @condition := (SELECT * FROM t2 WHERE t2.foo=='bar');
SELECT * FROM t1
LEFT JOIN (@condition) ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN (@condition) ON t1.id = t2.id