如何构建此查询...?

时间:2010-03-24 10:28:06

标签: sql mysql

考虑下表......

hotel     facilities
1       internet
1       swimming pool
1       wi-fi
1       parking
2       swimming pool
2       sauna
2       parking
3       toilets
3       bungee-jumping
3       internet
4       parking
4       swimming pool

我只需要选择有停车场,游泳池和网络的酒店......?

我制定了以下内容......

SELECT hotel
FROM   table
WHERE  facilties IN(internet, swimming pool, parking)

此查询选择具有至少一个选项的酒店。

但我需要的是一个查询,选择拥有所有选定设施的酒店......

感谢您的建议......

编辑:我还应该提到用户给出的选择数量,并且应该在运行时动态构建查询......

5 个答案:

答案 0 :(得分:4)

有三种方法可以做到这一点:

加入

SELECT hotel
FROM table t1
JOIN table t2 ON t1.hotel = t2.hotel AND t2.facilities = 'swimming pool'
JOIN table t3 ON t1.hotel = t3.hotel AND t3.facilities = 'parking'
WHERE t1.facilities = 'internet'

聚合

SELECT hotel
FROM table
GROUP BY hotel
WHERE facilities IN ('internet', 'swimming pool', 'parking')
HAVING COUNT(1) = 3

注意:这假设没有重复(酒店,设施)

EXISTS

SELECT hotel
FROM table t
WHERE facilities = 'internet'
WHERE EXISTS (SELECT 1 FROM table WHERE hotel = t.hotel AND facilities = 'swimming pool')
AND EXISTS (SELECT 1 FROM table WHERE hotel = t.hotel AND facilities = 'parking')

一个优秀的SQL优化器可能会将它们全部优化为相同但我发现MySQL在这个部门中可能有些不可预测,因此您需要使用有意义的数据集(> 100万行)对它们进行基准测试以确定哪个是最好的。

请参阅Oracle vs MySQL vs SQL Server: Aggregation vs Joins作为一些差异的示例。

答案 1 :(得分:3)

SELECT first.hotel
FROM table AS first
INNER JOIN table AS second
  ON first.hotel=second.hotel
INNER JOIN table AS third
  ON second.hotel=third.hotel
WHERE first.facilities='internet'
  AND second.facilities='swimming pool'
  AND third.facilities='parking'

答案 2 :(得分:1)

你可以使用GROUP BY和HAVING:

SELECT hotel
FROM table
WHERE facilties IN('internet', 'swimming pool', 'parking')
GROUP BY hotel
HAVING SUM(facilities = 'internet') AND SUM(facilities = 'swimming pool') AND SUM(facilities = 'parking')

答案 3 :(得分:1)

select t1.hotel
from tab t1,tab t2, tab,t3
where t1.hotel = t2.hotel and t2.hotel = t3.hotel
and t1.facilities = 'internet' and t2.facilities = 'parking'
and t3.facilities = 'swimming pool'

答案 4 :(得分:0)

另一种方法。

如果要动态构建查询:

Select Distinct hotel from facilities where 1=1
<logic here>
and facilities='internet'
<logic here>
and facilities='pool'
<logic here>
......

执行您的查询