对另一个查询的结果执行查询?
Posted
技术标签:
【中文标题】对另一个查询的结果执行查询?【英文标题】:Performing a query on a result from another query? 【发布时间】:2010-10-31 06:31:19 【问题描述】:我有一个查询:
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
返回类似:
Date Age
2009-06-25 0
2009-06-26 2
2009-06-27 1
2009-06-28 0
2009-06-29 0
然后我怎样才能对返回的行数进行计数..(在本例中为 5)和年龄的总和?只返回一行包含 Count 和 SUM?
Count SUM
5 3
谢谢
【问题讨论】:
【参考方案1】:您只需将查询包装在另一个中:
SELECT COUNT(*), SUM(Age)
FROM (
SELECT availables.bookdate AS Count, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
) AS tmp;
【讨论】:
【参考方案2】:通常您可以插入查询的结果(基本上是一个表)作为 FROM 子句源 另一个查询,所以会这样写:
SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
) AS SUBQUERY
【讨论】:
问题,不会为外部查询的每条记录运行子查询吗?或者结果会被缓存 sql server 最有可能做的就是运行一次子查询,然后对结果进行流聚合。您可以使用Include Actual Execution Plan
选项查看它的实际作用。【参考方案3】:
我不知道你是否甚至需要包装它。这行不通吗?
SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25'
AND date_add('2009-06-25', INTERVAL 4 DAY)
AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);
如果您的目标是返回两个结果集,那么您需要将其临时存储在某个地方。
【讨论】:
【参考方案4】:请注意,您的初始查询可能没有返回您想要的:
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate
您正在按预订日期分组,但您没有在查询的第二列使用任何分组功能。
您可能正在寻找的查询是:
SELECT availables.bookdate AS Date, count(*) as subtotal, sum(DATEDIFF(now(),availables.updated_at) as Age)
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
【讨论】:
以上是关于对另一个查询的结果执行查询?的主要内容,如果未能解决你的问题,请参考以下文章
mysql查询语句如何通过一个表查询出的数据对另一个表中的查询数据进行数据剔除