将mysql子查询转换为join

时间:2013-04-25 20:00:26

标签: mysql database join

我是mysql数据库的新手,我正在尝试创建一个使用连接的查询。 我写的现在的查询花了1秒的时间来执行,我做了研究,发现联接是减少执行时间的最佳解决方案,

我正在使用的查询是:

SELECT count(1) as total 
FROM `mytable` 
where pid IN (
     SELECT pid FROM `maps` 
     where `node_id` = (
          SELECT nid FROM shop 
          WHERE value = 'selling' 
            and parent = '170' 
            and  tid = 1
          )
     and  tid = 1
) 
and `pnumber` IN (
     select pnumber 
     FROM users_pro 
     where value = 'hulo' 
     and  tid = 1
)
and tid = 1

请大家多谢一点帮助。

谢谢..

1 个答案:

答案 0 :(得分:1)

SELECT count(distinct mytable.*) as total 
FROM mytable 
JOIN maps
  ON mytable.pid = maps.pid
  AND maps.tid = mytable.tid
JOIN shop
  ON maps.node_id = shop.nid
  AND shop.value = 'selling' 
  AND shop.parent = '170' 
  AND shop.tid = mytable.tid
JOIN users_pro 
  ON mytable.pnumber = users_pro.pnumber
  AND users_pro.value = 'hulo' 
  AND users_pro.tid = mytable.tid
WHERE mytable.tid=1