如何在mysql中只为表提供一次别名

时间:2015-02-26 10:36:55

标签: mysql sql

假设我有以下问题。

SELECT a.num Num ,   a.info infoA,
     b.info infoB,
     c.info infoC
FROM tbl_1 a
LEFT OUTER JOIN tbl_2 b USING (num)
LEFT OUTER JOIN tbl_3 c USING (num)
UNION
SELECT b.num Num , a.info infoA,
     b.info infoB,
     c.info infoC
FROM tbl_2 b
LEFT OUTER JOIN tbl_1 a USING (num)
LEFT OUTER JOIN tbl_3 c USING (num)
UNION
SELECT c.num Num , a.info infoA,
     b.info infoB,
     c.info infoC
FROM tbl_3 c
LEFT OUTER JOIN tbl_1 a USING (num)
LEFT OUTER JOIN tbl_2 b USING (num)

http://sqlfiddle.com/#!2/b0593f/12/0
问题是,我没有表名tbl_1,tbl_2和tbl_3,而是内部SELECT查询,例如:

FROM (SELECT...) a

我想只写一次表名(tbl_1,tbl_2,tbl_3),所以我不必多次重写我的内部SELECT查询。
我尝试过这样的事情,但它给了我一个sytax错误:

SELECT a.num Num ,   a.info infoA,
     b.info infoB,
     c.info infoC
FROM (SELECT...) a
LEFT OUTER JOIN b USING (num)
LEFT OUTER JOIN c USING (num)
UNION
SELECT b.num Num , a.info infoA,
     b.info infoB,
     c.info infoC
FROM (SELECT...) b
LEFT OUTER JOIN a USING (num)
LEFT OUTER JOIN c USING (num)
UNION
SELECT c.num Num , a.info infoA,
     b.info infoB,
     c.info infoC
FROM (SELECT...) c
LEFT OUTER JOIN a USING (num)
LEFT OUTER JOIN b USING (num)

但是当我编写这样的代码时,它可以工作。

SELECT a.num Num ,   a.info infoA,
     b.info infoB,
     c.info infoC
FROM (SELECT...) a
LEFT OUTER JOIN (SELECT...) b USING (num)
LEFT OUTER JOIN (SELECT...) c USING (num)
UNION
SELECT b.num Num , a.info infoA,
     b.info infoB,
     c.info infoC
FROM (SELECT...) b
LEFT OUTER JOIN (SELECT...) a USING (num)
LEFT OUTER JOIN (SELECT...) c USING (num)
UNION
SELECT c.num Num , a.info infoA,
     b.info infoB,
     c.info infoC
FROM (SELECT...) c
LEFT OUTER JOIN (SELECT...) a USING (num)
LEFT OUTER JOIN (SELECT...) b USING (num)

2 个答案:

答案 0 :(得分:1)

我不认为这会以任何形式发挥作用。 单独的查询仅由UNION运算符

组合

我建议您针对特定问题使用三种不同的视图。 鉴于您可以在数据库上创建视图。

答案 1 :(得分:0)

检查一下它是否可行

select sub.num Num , sub.info infoA, sub.info infoB, sub.info infoC 
from (

 SELECT a.num ,   a.info , b.info , c.info 
 FROM tbl_1 a
 LEFT OUTER JOIN tbl_2 b USING (num)
 LEFT OUTER JOIN tbl_3 c USING (num)
 UNION
 SELECT b.num , a.info , b.info , c.info 
 FROM tbl_2 b
 LEFT OUTER JOIN tbl_1 a USING (num)
 LEFT OUTER JOIN tbl_3 c USING (num)
 UNION
 SELECT c.num  , a.info , b.info , c.info 
 FROM tbl_3 c
 LEFT OUTER JOIN tbl_1 a USING (num)
 LEFT  OUTER JOIN tbl_2 b USING (num) )sub