查询逻辑,错误的想要结果mysql

时间:2014-01-06 22:30:44

标签: mysql

SELECT * FROM 
MobileApps as dtable 
WHERE (SELECT COUNT(*) as c 
       FROM app_details
       WHERE trackId=dtable.SourceID)=0 
ORDER BY id ASC 
LIMIT 0,2

问题是,id排序的前两个结果是app_details,因此前两个结果的COUNT(*)不等于0。但是MobileApps表中有更多可用的结果,等于0。

我认为它首先是SELECT * FROM app_details WHERE trackId=dtable.SourceID)=0然后是ORDER BY id ASC LIMIT 0,2,而不是相反,有什么方法可以解决这个问题?

由于

1 个答案:

答案 0 :(得分:1)

您的查询有效,但更好的方法是:

SELECT dtable.*
FROM MobileApps dtable
LEFT JOIN app_details d ON d.trackId = dtable.SourceID
WHERE d.trackId IS NULL
ORDER BY dtable.id
LIMIT 0, 2

或:

SELECT *
From MobileApps dtable
WHERE NOT EXISTS (SELECT *
                  FROM app_details d
                  WHERE d.trackId = dtable.SourceID)
ORDER BY id
LIMIT 0, 2

在此处查看所有3个版本:http://www.sqlfiddle.com/#!2/536db/2

对于大型表,您应该对它们进行基准测试,以查看哪个MySQL最佳优化。