MySQL嵌套,嵌套子查询没有得到外部变量

时间:2014-04-20 01:27:06

标签: mysql select in-subquery

我有一个花费表和一个日期表,由date_id和id ...

连接

我正在尝试做的是,从1查询获得所有花费的信息,加上所有花费的总和但是有限制和/或偏移

这是现在的查询

SELECT spendings.id, spendings.price, spendings.title, 
       dates.date, users.username, currencies.value,
       ( SELECT SUM(sum_table.price) 
         FROM (
             SELECT s.price
             FROM spendings s, dates d
             WHERE s.date_id = d.id 
               AND day(d.date) = 25
             LIMIT 2 OFFSET 0
         ) as sum_table
       ) AS sum_price
FROM spendings, dates, users, currencies
WHERE spendings.date_id = dates.id 
  AND day(dates.date) = 25 
  AND spendings.user_id = users.id 
  AND spendings.curr_id = currencies.id
LIMIT 2 OFFSET 0

输出

id  price   title   date       username value  sum_price
3   6.00    title1  2013-11-25 alex     €      21.00
4   15.00   title2  2013-11-25 alex     €      21.00

虽然有效,但前提是day(d.date) = 25的日期与此处的日期相同day(dates.date) = 25

如果我把day(d.date) = day(dates.date)放在看似逻辑的事情上,我会得到#1054 - Unknown column 'dates.date' in 'where clause'

如果有人想让这个更简单,请告诉我:)

1 个答案:

答案 0 :(得分:1)

尝试加入而不是使用嵌套的相关子查询:

SELECT spendings.id, spendings.price, spendings.title, 
      dates.date, users.username, currencies.value,
      y.sum_price
FROM spendings, dates, users, currencies
JOIN (
    SELECT day, SUM(sum_table.price) As sum_price
    FROM (
        SELECT day(d.date) As day,
               s.price
        FROM spendings s, dates d
        WHERE s.date_id = d.id 
          AND day(d.date) = 25
        LIMIT 2 OFFSET 0
    ) sum_table
    GROUP BY day
) y
ON y.day = day(dates.date)
WHERE spendings.date_id = dates.id 
  -- AND day(dates.date) = 25 <== commented since it's redundant now
  AND spendings.user_id = users.id 
  AND spendings.curr_id = currencies.id

一些评论:


建议不要使用旧的连接语法和逗号:FROM table1,table2,table2 WHERE
表达联接的推荐方式是&#34; new&#34; ANSI SQL连接语法:

FROM table1
[left|right|cross|[full] outer|natural] JOIN table2 {ON|USING} join_condition1
[left|right|cross|[full] outer|natural] JOIN table3 {ON|USING} join_condition2
....

实际上这是&#34;新语法&#34;现在已经很老了,因为我记得1992年 - 22年前已经出版了。在IT行业22年就像22岁。