无效的SQL查询

时间:2010-06-11 19:01:20

标签: sql mysql subquery exists mysql-error-1054

我有下一个查询,在我看来是有效的,但我一直收到错误告诉我“WHERE em.p4 = ue.p3”存在问题 - 未知列'ue.p3 'in'where where'

这是查询:

SELECT DISTINCT ue.p3
FROM 
    table1 AS ue INNER JOIN table2 AS e 
    ON ue.p3 = e.p3 
    WHERE 
        EXISTS(
            SELECT 1 FROM (
                SELECT (COUNT(*) >= 1) AS MinMutual 
                FROM table4 AS smm 
                WHERE 
                    smm.p1 IN (
                        SELECT sem.p3 FROM table3 AS sem 
                        INNER JOIN table2 AS em ON sem.p3 = em.p3 
                        WHERE em.p4 = ue.p3 AND 
                        sem.type = 'friends' AND em.p2 = 'normal' ) AND 
                    smm.p5 IN (
                        15000,15151
                    )
            ) AS Mutual WHERE 
        Mutual.MinMutual = TRUE) LIMIT 11

如果我执行EXISTS函数内的子查询,那么一切都是O.K。

请帮助!

2 个答案:

答案 0 :(得分:1)

出错的原因是您在关联时只能引用 一个 子查询图层。查看定义ue别名的位置,并计算FROM子句的数量,直到达到下一个引用。

我将您的查询重写为:

SELECT DISTINCT ue.p3
  FROM table1 AS ue 
  JOIN table2 AS e ON ue.p3 = e.p3 
 WHERE EXISTS(SELECT 1 AS MinMutual 
                FROM table4 AS smm 
                JOIN TABLE3 sem ON sem.p3 = smm.p1
                               AND sem.type = 'friends'
                JOIN TABLE2 em ON em.p3 = sem.p3
                              AND em.p3 = ue.p3
                              AND em.p2 = 'normal'
               WHERE smm.p5 IN (15000,15151)
            GROUP BY ? --needs a group by clause, in order to use HAVING
              HAVING COUNT(*) >= 1)  
 LIMIT 11

EXISTS如果满足则返回true - 它不会根据返回“true”的子查询进行评估。您不需要额外的子查询(无论如何都会导致问题)。

答案 1 :(得分:0)

AFAIK,到目前为止,这种相关查询在mysql中是不可行的。加入派生表而不是使用exists。