将子查询结果存储为列别名以供重用

时间:2012-10-11 10:04:26

标签: mysql count subquery

我正在尝试创建一个包含计数的列,但问题是我重新使用子查询来执行此操作,之前创建的临时表变得不可用,因为它不再存在。

我的问题是如何存储前一个子查询的结果,以便稍后可以在同一查询中对该结果运行某些内容?

首先是我的计数:

CREATE TEMPORARY TABLE _temp_unique_entity_manufacturers 
            (
              entityId INT(11),
              manufacturerRef INT(11),
              manufacturerName VARCHAR(255),
              KEY(entityId),
              KEY(manufacturerRef)
            )
            ENGINE=MEMORY AS 
              (SELECT DISTINCT entityRef AS entityId, manufacturer AS manufacturerRef, pm.name AS manufacturerName FROM enquiries, parts_trading, parts_manufacturers AS pm WHERE manufacturer = pm.id AND enquiryRef = enquiries.id)

然后在我的主要查询中,我使用此表,特别是这部分:

IF((SELECT COUNT(*) FROM _temp_unique_entity_manufacturers WHERE entityId = eo.id) > 0,
   (SELECT COUNT(*) FROM _temp_unique_entity_manufacturers WHERE entityId = eo.id),
   0
) AS manufacturers

第二个子查询失败,因为此时临时表已消失。有没有办法我不必一次又一次地写出相同的子查询?

1 个答案:

答案 0 :(得分:0)

        case when
         ((SELECT COUNT(*) FROM _temp_unique_entity_manufacturers WHERE entityId = eo.id) > 0) then
           (SELECT COUNT(*) FROM _temp_unique_entity_manufacturers WHERE entityId = eo.id) else
           0 end
        ) AS manufacturers
    --------------
    ex:
    select coname,(case when cond then result else second result end) as user_colname from
    tablename
----------------------
If condition implement in sql as case when statement