0

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

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

首先是我的计数:

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

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

4

1 回答 1

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
于 2012-10-11T10:06:18.890 回答