具有条件和的内连接

时间:2014-08-22 11:36:15

标签: mysql sql join

所以我有3个表,我需要获取按day_of_week列分组的价格列的总和,并且只返回总和最低的day_of_week的总和。 / p>

换句话说,所有场地都有许多服务,通过这些服务,他们有可用日期和价格。因此,场地的特定日期的价格是给定日期的服务价格的总和。我需要给定日期的总和,这是最低的,例如本周最低价。

这是我目前的查询:

SELECT * , SUM( ad.price ) AS venue_price
FROM venues AS v
JOIN services AS s ON v.id = s.serviceable_id
JOIN available_days AS ad ON s.id = ad.available_id
WHERE ad.available_type =  'Service'
AND s.type =  'basic'
AND ad.available =1
GROUP BY ad.day_of_week
HAVING venue_price < 500000
ORDER BY venue_price
LIMIT 1

这是一个小提琴:http://sqlfiddle.com/#!2/37ee20/1/0

当我有一个场地时,这是有效的,但问题是它应该得到所有场地,其场地价格低于500000.我如何才能选择具有最低价格的available_days条目,而不是限制它只有一个场地?

1 个答案:

答案 0 :(得分:1)

如果您需要最低金额的记录,请按price对其进行排序,并将LIMIT设为1

SELECT * , SUM( ad.price ) AS price
FROM venues AS v
JOIN services AS s ON v.id = s.serviceable_id
JOIN available_days AS ad ON s.id = ad.available_id
WHERE ad.available_type =  'Service'
AND s.type =  'basic'
AND ad.available = 1
ORDER BY price ASC
LIMIT 1