是否可以以某种方式存储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')
会很好。
答案 0 :(得分:4)
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