查询需要很长时间

时间:2015-03-28 17:30:12

标签: mysql sql

我正在做这个SQL代码吗?该查询有效,但需要很长时间,161秒(设置为LIMIT 2)。有没有办法优化它?

 SELECT p.itemid as `id`,
    p.title as `name`,
    pb.data_txt as `birthdate`,
    pc.data_txt as `growth`,
    pd.data_txt as `eyes`,
    pe.data_txt as `desc`,
    pf.data_txt as `weight`,
    pg.data_txt as `sex`,
    ph.data_txt as `hair`,
    pi.data_txt as `dimensions`,
    pj.data_txt as `lang`,
    pk.data_txt as `school`,
    pl.data_txt as `know`,
    p.image as `image` 

FROM  `jos_sobi2_item` p 
    INNER JOIN `jos_sobi2_fields_data` AS pb ON pb.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS pc ON pc.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS pd ON pd.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS pe ON pe.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS pf ON pf.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS pg ON pg.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS ph ON ph.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS pi ON pi.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS pj ON pj.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS pk ON pk.itemid  = p.itemid
    INNER JOIN `jos_sobi2_fields_data` AS pl ON pl.itemid  = p.itemid

WHERE
      pb.fieldid = 16 AND
      pc.fieldid = 17 AND
      pd.fieldid = 21 AND
      pe.fieldid = 13 AND
      pf.fieldid = 18 AND
      pg.fieldid = 19 AND
      ph.fieldid = 20 AND
      pi.fieldid = 22 AND
      pj.fieldid = 25 AND 
      pk.fieldid = 23 AND
      pl.fieldid = 24

LIMIT 2

我认为INNER JOIN的一部分很糟糕。

1 个答案:

答案 0 :(得分:0)

请尝试使用条件聚合:

SELECT p.itemid as `id`, p.title as `name`,
       max(case when fd.fieldid = 16 then data_txt end) as birthdate,
       max(case when fd.fieldid = 17 then data_txt end) as growth,
       . . .
FROM  `jos_sobi2_item` p INNER JOIN
      `jos_sobi2_fields_data` fd
      ON fd.itemid = p.itemid
GROUP BY p.itemId, p.title;

您可以添加任意数量的字段,添加更多字段对性能影响不大。

如果你真的想要这个更快,你可以在第一个表上执行limit

SELECT p.itemid as `id`, p.title as `name`,
       max(case when fd.fieldid = 16 then data_txt end) as birthdate,
       max(case when fd.fieldid = 17 then data_txt end) as growth,
       . . .
FROM  (select p.*
       from `jos_sobi2_item` p
       limit 2
      ) p INNER JOIN
      `jos_sobi2_fields_data` fd
      ON fd.itemid = p.itemid
GROUP BY p.itemId, p.title;