1

好的,首先对标题感到抱歉,但我找不到更好的 :(
这是问题所在:
我有两个表,properties并且properties_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 BYand HAVING
选择中的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语句......

4

1 回答 1

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 nrofxWHERE.

HAVING bedrooms >= 3 AND bathrooms >= 2

您可以在此处查看特定房间的编号。

于 2012-06-15T14:50:09.830 回答