使用左连接从其他表中获取最低价格

时间:2015-07-28 15:29:08

标签: php jquery mysql join left-join

我使用左连接从两个表中获取数据, tour tour_price 但是从定价表中我无法获取最低价格

这是我的查询

SELECT t1.id,t1.tour_title,t2.price 
FROM tours t1 
LEFT JOIN tour_dates t2 ON t1.id=t2.tour_id 
WHERE t1.status = '1' AND ( t2.price between 40 AND 100 ) 
GROUP BY t2.tour_id 
ORDER BY t2.price DESC

我认为我需要做一些小改动,但无法理解。

请提供一些帮助。 谢谢。

2 个答案:

答案 0 :(得分:2)

It should be:

SELECT t1.id, t1.tour_title, MIN(t2.price) min_price
FROM tours t1
LEFT JOIN tour_dates t2 ON t1.id = t2.tour_id AND t2.price BETWEEN 40 AND 100
WHERE t1.status = '1'
GROUP BY t1.id
ORDER BY min_price DESC
  • Use MIN(t2.price) to get the minimum price.
  • Since you're using LEFT JOIN, the conditions on the second table should be put in the ON clause. Otherwise, the tours that don't have any matching dates will be filtered out, because t2.price will be NULL.
  • Don't use a column from the second table in GROUP BY, because it will be NULL if there's no match. All the tours with no dates would then be grouped together as one result, which is not what you usually want.

If you don't want the result to include tours with no dates, you should be using INNER JOIN rather than LEFT JOIN. If you're confused about the difference, see

A Graphical Explanation of SQL Joins

答案 1 :(得分:1)

Edit: This answer is for MS SQL and not for MySQL. Thanx Barmar for the comment.

Try to use the MIN() function on t2.price.

You also need to group by the values that you do a select on except for MIN() because it is a aggregate function.

SELECT t1.id,t1.tour_title, MIN(t2.price )
FROM tours t1 
LEFT JOIN tour_dates t2 ON t1.id=t2.tour_id 
WHERE t1.status = '1' AND ( t2.price between 40 AND 100 ) 
GROUP BY t1.id,t1.tour_title
ORDER BY MIN(t2.price ) DESC