我正在尝试做这样的事情:
SELECT t1.*,
t2.*
FROM (SELECT *
FROM USER) AS t1,
(SELECT *
FROM t1) AS t2
它在MySQL中不起作用。有可能像以上那样吗?我的另一个选择是获取最后一个子查询并围绕主查询“包装”它。想法?
答案 0 :(得分:2)
使用:
SELECT t1.*,
t2.*
FROM (SELECT *
FROM USER) AS t1,
(SELECT *
FROM (SELECT *
FROM USER) AS t1) AS t2
WITH
语法允许您构建在CTE之上:
WITH t1 AS (
SELECT * FROM USER), -- comma separates them
t2 AS (
SELECT * FROM t1)
SELECT t1.*, t2.*
FROM t1, t2
..但MySQL不支持WITH子句。
答案 1 :(得分:1)
为什么不
SELECT t1.*, t2.* FROM USER as t1, USER as t2
?您还应该添加一个条件,否则会产生大量的行。
现在,如果您打算询问如何引用上一个子查询,您应该重复它并添加所需的额外条件:
SELECT t1.*, t2.* FROM (SELECT bar FROM foo WHERE baz=1) as t1,
(SELECT bluz,bar FROM foo WHERE baz=1 AND quux = 0) as t2 WHERE t2.bar = t1.bar
另一种选择是使用子查询(t1)
创建视图或临时表答案 2 :(得分:1)
如果2个表的列数相同,则可以使用UNION
e.g。
SELECT *
FROM USER
UNION
SELECT *
FROM t1
如果它们没有相同的列,则需要以某种方式加入表格,例如使用外键。 E.g。
SELECT *
FROM USER as t1
JOIN t1 as t2 (on t1.id = t2.id)
答案 3 :(得分:0)
我认为您的实际查询要复杂得多。是否有可能创建一个代表子查询的视图,然后你可以使用像Vinko Vrsalovic建议的更简单的选择语句。