SELECT *
FROM table_a
LEFT JOIN table_b ON (table_b.id = table_a.id)
WHERE table_b.created BETWEEN ? AND ?
AND table_b.manager IN(
SELECT DISTINCT (b.id)
FROM table_b a
INNER JOIN table_b b ON a.manager = b.id
AND b.user_level > 0
AND b.id != 1
)
如何在上述查询中删除子查询并使用JOINS
由于
答案 0 :(得分:0)
MySQL 5.5(和更低版本)的优化器为IN (SELECT ...)
生成DEPENDENT SUBQUERY
,这意味着找到了每个匹配的行,IN(SELECT ...)
被评估为使选择变慢。< / p>
简单优化查询是使内联视图如下:
SELECT *
FROM table_a LEFT JOIN table_b ON (table_b.id = table_a.id)
INNER JOIN (
SELECT DISTINCT b.id AS id
FROM table_b a
INNER JOIN table_b b ON a.manager = b.id
AND b.user_level > 0
AND b.id != 1
) x ON table_b.manager = x.id
WHERE table_b.created BETWEEN ? AND ?
AND x.id IS NOT NULL;
我认为avobe查询会产生与你自己相同的效果。
最后,DISTINCT
不是函数。请使用SELECT DISTINCT b.id
而不是SELECT DISTINCT (b.id)