3

我无法解决这个问题......希望有人能帮助我......我得到了这个查询:

  SELECT V.ID, ....,

  (SELECT SUM(D.value)
   FROM E 
   LEFT JOIN I   ON E.ID = I.f1 
   LEFT JOIN D   ON I.f2 = D.ID
   WHERE E.ID_ven = V.ID) inc          

   FROM ven V
   WHERE V.ID=....

问题是:我必须 SUM(D.values) 但只能在 DISTINCT D.ID 值上。我试图用子查询:

  SELECT V.ID,...., 

  (SELECT SUM(D.value)    FROM (
      SELECT DISTINCT D.ID, D.value
      FROM E 
      LEFT JOIN I    ON E.ID = I.f1 
      LEFT JOIN D   ON I.f2 = D.ID
      WHERE E.ID_ven = V.ID) A1   ) inc        
  FROM ven V    WHERE V.ID=....

但是mysql给了我:错误代码:1054 Unknown column 'V.ID' in 'where Clause'

4

1 回答 1

1

SELECT您可以使用GROUP BY来完成“每个 id 的值的总和”,而不是使用两个双嵌套语句。

试试这样的查询:

SELECT V.ID,...., 
    (
        SELECT
            D.ID, SUM(D.value)
        FROM E 
            LEFT JOIN I ON E.ID = I.f1 
            LEFT JOIN D ON I.f2 = D.ID
        WHERE
            E.ID_ven = V.ID
        GROUP BY
            D.ID
    ) inc        
FROM ven V
WHERE V.ID=....

通过删除第二个嵌套查询,您应该能够V.ID在子查询中访问ven,当然它是表中的实际列。

于 2012-11-30T13:33:02.233 回答