0

我正在尝试根据 IF 语句恢复一个字符串,但它非常慢。

它与第一个子查询有关,但我不确定如何重新排列它以恢复相同的结果但速度更快。

这是我的 SQL:

SELECT IF
(
    (
        SELECT COUNT(*)
        FROM 
            (
                SELECT DISTINCT enquiryId, type 
                FROM parts_enquiries, parts_service_types AS pst 
                WHERE parts_enquiries.serviceTypeId = pst.id
            ) AS parts
        WHERE parts.enquiryId = enquiries.id
    ) > 1, 'Mixed',
    (
        SELECT DISTINCT type 
        FROM parts_enquiries, parts_service_types AS pst 
        WHERE parts_enquiries.serviceTypeId = pst.id AND enquiryId = enquiries.id
    )
) AS partTypes
FROM  enquiries,
entities
WHERE enquiries.entityId = entities.id

我怎样才能让它更快?


我在下面修改了我的原始查询,但我收到子查询返回多行的错误:

SELECT
(SELECT
   CASE WHEN COUNT(DISTINCT type) > 1 THEN 'Mixed' ELSE `type` END AS type
FROM parts_enquiries 
INNER JOIN parts_service_types AS pst ON parts_enquiries.serviceTypeId = pst.id
INNER JOIN enquiries ON parts_enquiries.enquiryId = enquiries.id
INNER JOIN entities ON enquiries.entityId = entities.id
GROUP BY enquiryId) AS partTypes
FROM  enquiries,
entities
WHERE enquiries.entityId = entities.id

解释结果

4

2 回答 2

1

请查看此查询是否产生相同的结果:

SELECT 
   enquiryId, 
   CASE WHEN COUNT(DISTINCT type) > 1 THEN 'Mixed' ELSE `type` END AS type
FROM parts_enquiries 
INNER JOIN parts_service_types AS pst ON parts_enquiries.serviceTypeId = pst.id
INNER JOIN enquiries ON parts_enquiries.enquiryId = enquiries.id
INNER JOIN entities ON enquiries.entityId = entities.id
GROUP BY enquiryId

但NB的评论仍然有效。要查看是否使用了和索引以及其他信息,我们需要查看EXPLAIN和表定义。

于 2013-03-01T10:42:37.370 回答
0

这应该可以得到你想要的。

我将首先预先查询您的零件查询和零件服务类型,查找零件“类型”的计数和最小值,按查询 ID 分组。

然后,针对该结果运行 IF() 。如果不同计数 > 0,则为“混合”。如果只有一个,因为我做了 MIN(),它只会有你想要的那个值的描述。

SELECT
      E.ID
      IF ( PreQuery.DistTypes > 1, 'Mixed', PreQuery.FirstType ) as PartType
   from 
      Enquiries E
         JOIN ( SELECT
                      PE.EnquiryID,
                      COUNT( DISTINCT PE.ServiceTypeID ) as DistTypes,
                      MIN( PST.Type ) as FirstType
                   from 
                      Parts_Enquiries PE
                         JOIN Parts_Service_Types PST
                            ON PE.ServiceTypeID = PST.ID
                   group by 
                      PE.EnquiryID ) as PreQuery
            ON E.ID = PreQuery.EnquiryID
于 2013-03-01T10:47:18.250 回答