在mysql if语句中使用alisas

时间:2015-05-11 10:47:49

标签: mysql

我试图找到一个表中的两个指定行中的哪个costCentreClientGroups在另一个表中具有最相关的记录costCentreClientGroupMembership

所以我有

SELECT IF((SELECT COUNT(*) FROM 
db6901371_clients.costCentreClientGroupMembership c1
JOIN db6901371_clients.costCentreClientGroups c2 
ON c1.costCentreClientGroupID = c2.costCentreClientGroupID
WHERE c2.costCentreClientGroupID = '1a64fa70-aa0d-11e4-8c36-776ec28246d8' 
GROUP BY c2.costCentreClientGroupID) > 
(SELECT COUNT(*) FROM db6901371_clients.costCentreClientGroupMembership c3
JOIN db6901371_clients.costCentreClientGroups c4 
ON c3.costCentreClientGroupID = c4.costCentreClientGroupID
WHERE c4.costCentreClientGroupID = '1a7582f0-aa0d-11e4-8c36-776ec28246d8' 
GROUP BY c4.costCentreClientGroupID)
, c2.costCentreClientLeaderID, c4.costCentreClientLeaderID)
as costCentreClientLeaderID

IF条款单独工作

因此;

SELECT COUNT(*) FROM db6901371_clients.costCentreClientGroupMembership c1
JOIN db6901371_clients.costCentreClientGroups c2 
ON c1.costCentreClientGroupID = c2.costCentreClientGroupID
WHERE c2.costCentreClientGroupID = '1a64fa70-aa0d-11e4-8c36-776ec28246d8' 
GROUP BY c2.costCentreClientGroupID

作品

但是当我将两者结合起来时,整体陈述给出了

字段列表中的未知表'c2'

1 个答案:

答案 0 :(得分:0)

问题是子查询的使用。 在子查询的结束表后使用别名,因此别名超出范围。也就是说,它不被认可。

您可以通过将子查询移动到from子句来解决此问题。我的偏好是更改为查询以使用条件聚合:

SELECT (CASE WHEN SUM(g.costCentreClientGroupID = '1a64fa70-aa0d-11e4-8c36-776ec28246d8') >
                  SUM(g.costCentreClientGroupID = '1a7582f0-aa0d-11e4-8c36-776ec28246d8')
            THEN MAX(CASE WHEN g.costCentreClientGroupID = '1a64fa70-aa0d-11e4-8c36-776ec28246d8'
                          THEN g.costCentreClientLeaderID
                     END)
            ELSE MAX(CASE WHEN g.costCentreClientGroupID = '1a7582f0-aa0d-11e4-8c36-776ec28246d8'
                          THEN g.costCentreClientLeaderID
                     END)
      END)
FROM db6901371_clients.costCentreClientGroupMembership gm JOIN
     db6901371_clients.costCentreClientGroups g
     ON gm.costCentreClientGroupID = g.costCentreClientGroupID
WHERE g.costCentreClientGroupID IN ('1a64fa70-aa0d-11e4-8c36-776ec28246d8', '1a7582f0-aa0d-11e4-8c36-776ec28246d8')

为什么查询中需要表costCentreClientGroupMembership并不明显。似乎没有使用它。