Mysql UNION作为带有别名字段的子查询

时间:2016-07-01 09:03:18

标签: mysql subquery union

我有一个UNION查询(我简化了我的工作查询,因此更容易阅读):

SELECT count(*) FROM 
(SELECT DISTINCT `tableA`.`Store Name` FROM `tableA` UNION SELECT DISTINCT `tableB`.`Store Name` FROM `tableB`) t

这样可以正常工作,并产生一个列名为COUNT(*)

的数字

我想将此值作为另一个查询中的另一列,所以我这样做:

SELECT DISTINCT `tableC`.`id as PID,
(SELECT count(*) from (SELECT DISTINCT `tableA`.`Store Name` FROM `tableA` UNION SELECT DISTINCT `tableB`.`Store Name` FROM `tableB`) t) AS noofstores
WHERE
.....;

但它不会工作!我究竟做错了什么?这是更大查询的一部分,当我执行

时,所有其他子查询都可以正常工作
,
(SELECT .... ) AS column_name
,

抱歉错误描述不佳。更新: 这是我的完整查询:

SELECT DISTINCT
`tableC`.`id` as PID,
(SELECT count(*) 
from 
(SELECT DISTINCT `tableA`.`Store Name` FROM `tableA` WHERE  `tableA`.`id` = PID 
 union 
 SELECT DISTINCT `tableB`.`Store Name` FROM `tableB` WHERE  `tableB`.`id` = PID) t) AS mycolumn_name
 FROM 
 `tableC`

看起来我的联盟是正确的,但问题是我在联盟中遇到的PID:

1054 - 'where子句'

中的未知列'PID'

那么我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

内部子查询中不存在PID列,仅在外部查询中。您可以在tableC上的union中的两个查询中进行内部联接并在那里进行过滤,或者您需要在union查询中返回id列并将它们连接到它们上以进行过滤。

select tableC.id as PID, count(distinct storename) 
from
    (select distinct id, storename from tableA
     union
     select distinct id, storename from tableB) t1
inner join tableC on t1.id=tableC.id
group by tableC.id

答案 1 :(得分:0)

您必须加入两个表才能获得结果

  SELECT DISTINCT c.id as PID from  table C inner join 
        (SELECT count(*) from 
(SELECT DISTINCT `tableA`.`Store Name` as st 
 FROM `tableA` UNION  SELECT DISTINCT `tableB`.`Store Name` as st
    FROM `tableB`) t on t.some_id=c.id WHERE