使用多列上的1 / n表使用子句筛选字段

时间:2012-06-15 13:49:07

标签: php mysql

好的,首先抱歉标题,但我找不到更好的一个:(
这是问题:
我有两个表propertiesproperties_rooms,它们通过符号ID相互链接。

properties table:

+---------------+------------+
| id_properties | pr_title   |
+---------------+------------+
|             1 | test       |
|             2 | dummy      |
+---------------+------------+

properties_rooms table:
+---------------+-------------------+--------------+----------+
| id_prop_rooms | pro_id_properties | pro_id_rooms | pro_size |
+---------------+-------------------+--------------+----------+
|             1 |                 1 |            4 |     5.00 |
|             2 |                 1 |           18 |    17.00 |
|             3 |                 2 |            6 |    12.00 |
|             4 |                 2 |           24 |    11.00 |
|             5 |                 1 |            4 |    10.00 |
|             6 |                 1 |            6 |    10.00 |
|             7 |                 1 |            6 |    12.00 |
+---------------+-------------------+--------------+----------+

我正在进行高级搜索,用户可以搜索超过同类房间的房产(即两间卧室,三间浴室等)。

可悲的是,我发现自己陷入了困境,因为我不能用多个子句“过滤”相同的数据集;如果我只需要过滤一个就没有问题,因为我可以使用HAVING子句。

我做了这个选择:

SELECT id_properties, pro_id_rooms, COUNT(*) as total, 
        IF ((pro_id_rooms = 4 AND COUNT(*) >= 2) OR (pro_id_rooms = 6 AND COUNT(*) >= 2), 1, 0) as flag
FROM `properties`
INNER JOIN properties_rooms ON id_properties = pro_id_properties
WHERE id_properties IN (4,10)
GROUP BY id_properties, pro_id_rooms
ORDER BY id_properties

IN子句中,有些属性我知道他们至少有一个被请求的房间。它们来自之前的查询,因为我必须使用GROUP BYHAVING select中的IF部分是在运行时构建的,因为我从请求中获取了信息 这是结果:

+---------------+--------------+-------+------+
| id_properties | pro_id_rooms | total | flag |
+---------------+--------------+-------+------+
|             1 |            4 |     2 | 1    |
|             1 |            6 |     2 | 1    |
|             1 |           18 |     1 | 0    |
|             2 |            6 |     1 | 0    |
|             2 |           24 |     1 | 0    |
+---------------+--------------+-------+------+

我认为它可以工作,我只需要添加一个HAVING flag > 0而且我已经完成了。

我的问题是,有什么更好的吗? 表格不是很大:属性可能是1k,房间大约是10k 我担心,如果用户放置太多房间,查询将变成一个巨大的IF声明......

1 个答案:

答案 0 :(得分:0)

SELECT id_properties, SUM(pro_id_rooms = 4) AS bedrooms, SUM(pro_id_rooms = 6) AS bathrooms
FROM `properties`
INNER JOIN properties_rooms ON id_properties = pro_id_properties
WHERE id_properties IN (4,10)
GROUP BY id_properties
HAVING bedrooms >= 3 AND bathrooms >= 2

更改

SUM(pro_id_rooms = 4) AS bedrooms, SUM(pro_id_rooms = 6) AS bathrooms

对于用户选择的每个复选框,您需要SUM(pro_id_rooms = x) AS nrofx中的WHERE

HAVING bedrooms >= 3 AND bathrooms >= 2

这是您检查特定房间号码的地方。