MySQL使用WHERE语句跨表选择COUNT()?

时间:2012-09-12 01:41:23

标签: mysql performance count where

到目前为止,我使用了一个子选择,但是一些研究告诉我使用子选择(特别是在大型表格上)是不好的,因为它们的性能较差。

现在就是我得到的:

SELECT COUNT( riddims.riddim ) AS rc, 
(
    SELECT COUNT( tunes.tune )
    FROM tunes
    WHERE tunes.tune NOT
    IN (
        ''
    )
) AS tc
FROM riddims
WHERE riddims.riddim NOT
IN (
    ''
)

表格如下:

riddims:
riddim | genre | image

tunes:
riddim | artist | tune

我正在玩“加入”,但无法确定一个有效的查询。我需要的是与STACKOVERFLOW COUNT FROM MULTIPLE TABLES类似的东西,其效果比上述解决方案更为出色。

我的目标是执行显示以下输出的查询:

riddims | tunes | artist
100     | 400   | 2
  • WHED riddims NOT IN('')
  • WHERE Tunes NOT IN('')
  • WHERE artist ='some artist'

这就是我的开始,但它显然走向了错误的方向:

SELECT COUNT(riddims.riddim) AS rc, COUNT(tunes.tune) AS tc FROM riddims LEFT JOIN tunes ON riddims.riddim = tunes.riddim

1 个答案:

答案 0 :(得分:1)

您是否尝试这样做:

select riddims, tunes, artists
from (select count(*) as riddims from riddims where . . . ) r cross join
     (select count(*) as tunes from tunes where tunes not in  . . .) t cross join
     (select count(*) as artists from tunes where artist not in . . .) a

您的表似乎没有连接,至少对于此查询而言。可能的性能问题是,每行调用select中的子查询一次。通过将它们放在FROM子句中,可以消除这个可能的问题。