0

I'm having a bit of a SQL n00b moment. Say I have a property website with two tables: properties and features, with a table that joins them. If I have a search form, how can I structure my query to select only properties with all of the selected criteria?

For example, criteria would be POSTed in the form of an array from checkboxes:

Array
(
    [features] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 5
        )
)

How can I select records from my properties that have features with the IDs of 1, 2 and 5 (and possibly others), but properties that only have one or two are not matched?

4

2 に答える 2

3

関心のある機能の結合テーブルをフィルター処理し、プロパティでグループ化し、結果セットを必要な数のレコードを含むグループのみに制限できます。

SELECT   properties.*
FROM     properties JOIN propfeatures USING (property_id)
WHERE    propfeatures.feature_id IN (1,2,5)
GROUP BY property_id
HAVING   COUNT(DISTINCT propfeatures.feature_id) = 3

もちろん、一意性が保証されている場合は、DISTINCT操作を節約してCOUNT(*)代わりに使用できます。

于 2012-07-23T11:51:18.993 に答える
0

propertiesfeaturesテーブルがテーブル内の列によってテーブル内に結合されているfeature_id場合propertiesidこれをfeatures行うことができます。

SELECT a.* FROM `properties` AS a JOIN `features` AS b WHERE 
a.`feature_id`=b.`id` AND b.`id` IN (1,2,5) ORDER BY a.`feature_id` ASC;

お役に立てれば。

于 2012-07-23T12:00:02.597 に答える