Mysql

通過子查詢選擇多個列

  • June 12, 2019

我正在嘗試從以下查詢中的子查詢中選擇 2 列,但無法這樣做。嘗試創建別名表,但仍然無法獲取它們。

SELECT
 DISTINCT petid,
 userid,
 (SELECT MAX(comDate) FROM comments WHERE petid=pet.id) AS lastComDate,
 (SELECT userid FROM comments WHERE petid=pet.id ORDER BY id DESC LIMIT 1) AS lastPosterID
FROM 
 pet LEFT JOIN comments ON pet.id = comments.petid
WHERE 
 userid='ABC'      AND 
 deviceID!='ABC'   AND 
 comDate>=DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MONTH);

基本上,我試圖從同一行獲取lastComDate& lastPosterID——該行是特定寵物評論中的最新行。請建議我如何以有效的方式獲得它們。

上面的查詢有效,但似乎有點矯枉過正,因為同一行被提取了兩次。此外,該ORDER BY子句比聚合函式慢得多——正如我在分析查詢時發現的那樣。因此,將不勝感激避免排序的解決方案。

SELECT DISTINCT petid, userid, lastComDate, lastPosterId
FROM 
   pet 
   LEFT JOIN comments ON pet.id = comments.petid 
   LEFT JOIN (
       SELECT MAX(comDate), userid, petid FROM comments GROUP BY userid
   ) a ON a.petid = pet.id
WHERE 
   userid='ABC' 
   AND deviceID!='ABC' 
   AND comDate>=DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MONTH)
;

如果性能在某處受到影響,您還可以將子查詢拉出到臨時表中。

鑑於您的表格如下所示:

create table pet (id int, userid int, deviceid int);
create table comments (id int, petid int, comdate date);

這個查詢應該可以解決問題:

SELECT 
       p.id, 
       p.userid,
       (SELECT MAX(comDate)
        FROM comments
        WHERE petid = p.id
        AND comDate >= DATE_SUB(
                CURRENT_TIMESTAMP, INTERVAL 2 MONTH)
              ) AS lastComDate,
       (SELECT userid
        FROM comments
        WHERE petid = p.id
        AND comDate >= DATE_SUB(
             CURRENT_TIMESTAMP, INTERVAL 2 MONTH
        ) ORDER BY id DESC LIMIT 1) AS lastPosterID
   FROM 
       pet p

   WHERE 
       p.userid=1
       AND p.deviceID!=1

引用自:https://dba.stackexchange.com/questions/34673