WHERE IN SELECT替换连接

时间:2018-05-24 12:59:02

标签: mysql sql

我有这个SQL查询:

SELECT
    count(*) as count
FROM
    USERS.Names p1
WHERE
    p1.rowid IN (
            SELECT p2.rowid
            FROM USERS.Names p2
            WHERE
                p2.Id = p1.Id AND p2.status = p1.Status
                AND p2.DateTo = (SELECT max(p3.dateTo)
                                FROM USERS.Names p3
                                WHERE p3.entityid = p1.Id
                                        AND p3.status = p1.Status
                                        AND p3.Code = p2.Code)
  )
  AND p1.Status = 1
  AND p1.Id >= 12
  AND p1.Id < 31308;

我删除嵌套的SELECT并用JOIN替换它们?该请求已经有效了很长时间

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
    count(*) as count
FROM
    USERS.Names p1
INNER JOIN
    SELECT (
        MAX(dateto) MaxDateto
    FROM USERS.Names) p2
        ON p1.dateto = p2.MaxDateto
WHERE
    p1.Status = 1
    AND p1.Id >= 12
    AND p1.Id < 31308;

答案 1 :(得分:0)

您可能正在寻找以下内容:

SELECT count(1) count
  FROM Names p3 
            JOIN 
                (
                 SELECT max(p1.dateTo) dateTo_max
                   FROM Names p1 JOIN Names p2 
                     ON ( p2.entityid = p1.Id )  
                  WHERE p1.dateTo = p2.dateto
                    AND p1.Status = 1
                    AND p1.Id between 12 AND 31307) p4 
                     ON ( p3.dateto = p4.dateTo_max );