我有一个支出表和一个日期表,它们由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(d.date) = 25与此处的外层day(dates.date) = 25

如果取而代之的是我将day(d.date) = day(dates.date)放在逻辑上,那我会得到#1054 - Unknown column 'dates.date' in 'where clause'

如果有人想简化这个,请告诉我:)

===============>>#1 票数: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语法: FROM table1,table2,table2 WHERE
表示连接的推荐方式是“新的” 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
....

实际上,这种“新语法”现在已经很老了,因为据我所记得,它是在1992年-22年前发布的。 在IT行业中,22年就像22岁。


  ask by C Alex translate from so

未解决问题?本站智能推荐: