如何在5个嵌套表上执行MySQL Left Join?

时间:2019-01-11 10:33:59

标签: mysql nested left-join

我具有以下数据库结构:

enter image description here

其中prefix_dt表直接与prefix_ueprefix_di表连接,而prefix_di表直接与prefix_drprefix_dp表连接。

我当前正在运行以下MySQL查询,以从所有5个表中获取数据:

SELECT 
  SQL_CALC_FOUND_ROWS pdt.id as id, 
  CONCAT(
    pue.first_name, ' ', pue.last_name
  ) as name, 
  pdi.download, 
  pdi.version as version, 
  pdi.release_title, 
  pdt.accepted_licence as accepted_licence, 
  pdt.download_date as download_date 
FROM 
  prefix_dt pdt 
LEFT JOIN prefix_ue pue ON pue.users_id = pdt.user_id 
LEFT JOIN (
  SELECT 
    pdi.id, 
    pdi.version as version, 
    pdr.title as release_title, 
    pdp.title as download 
  FROM 
    prefix_di pdi 
    LEFT JOIN prefix_dr pdr ON pdr.id = pdi.release_id 
    LEFT JOIN prefix_dp pdp ON pdp.download_id = pdi.download_id 
  WHERE 
    pdp.language_id = 1
  ) as pdi ON pdt.download_item_id = pdi.id 
WHERE 
  1 = 1 
GROUP BY 
  pdt.id 
ORDER BY 
  id asc 
LIMIT 
  0 , 10

我在prefix_dt表中有3百万条记录,因此该查询大约需要20秒才能运行。我也尝试过子查询,但是没有任何运气。我仅限于利用相同的数据库结构。有谁知道一种更好的方法来在单个查询中获取数据,而不用花费20秒钟以上的时间?

以下是带有示例数据的数据库提琴: https://www.db-fiddle.com/f/eEGX8Z2gxrEzhptZsDF9hR/1

0 个答案:

没有答案