簡體   English   中英

優化子查詢的最佳方法

[英]Best way to optimize a subquery

我需要得到signature_filesignature_datestatus_id 每個都來自子查詢,實際上,這是我的代碼。

有最好的方法來優化這個查詢,也許只有一個子查詢?

示例(預期)

SELECT 
    ID, fck, f1, 
    (SELECT f2, f3 FROM tbl2 Y WHERE Y.ID = T.fck) AS f2, f3
FROM 
    tbl1 T

我看的那張桌子總是一樣的......

   SELECT d.*, cd.*,
 
   ( SELECT s.cnt_man_doc_signature_file
     FROM cnt_man_doc_signatures s
     WHERE s.cnt_man_doc_signature_document_id = d.cnt_man_doc_id
     ORDER BY s.cnt_man_doc_signature_id DESC
     LIMIT 1
   )
     AS signature_file,

   ( SELECT s.cnt_man_doc_signature_date
     FROM cnt_man_doc_signatures s
     WHERE s.cnt_man_doc_signature_document_id = d.cnt_man_doc_id
     ORDER BY s.cnt_man_doc_signature_id DESC
     LIMIT 1
   )
     AS signature_date,

   ( SELECT s.cnt_man_doc_signature_status_id
     FROM cnt_man_doc_signatures s
     WHERE s.cnt_man_doc_signature_document_id = d.cnt_man_doc_id
     ORDER BY s.cnt_man_doc_signature_id DESC
     LIMIT 1
   )
     AS status_id

   FROM      cnt_man_docs d
   LEFT JOIN cnt_man_class_doc cd ON cd.cnt_man_class_doc_id = d.cnt_man_doc_class_id
   WHERE     cnt_man_doc_folder_id = ? 

正如 Marko 指出的那樣:您正在使用 4 個具有不同列選擇的類似子查詢。 您可以改為只使用該子查詢一次並選擇所需的列:

    SELECT d.*, 
    cd.*, 
    s.cnt_man_doc_signature_file, 
    s.snt_man_doc_signature_doc, 
    s.cnt_man_doc_signature_status_id

       FROM      cnt_man_docs d
       LEFT JOIN cnt_man_class_doc cd ON cd.cnt_man_class_doc_id = d.cnt_man_doc_class_id
       LEFT JOIN cnt_man_doc_signatures s ON s.cnt_man_doc_signature_document_id = d.cnt_man_doc_id
       WHERE     cnt_man_doc_folder_id = ? 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM