Mysql:获取具有所有这些关系的所有结果

时间:2010-11-05 14:03:16

标签: mysql

我有两张桌子:

  objects                    object_features
-------------              -------------------
id                         id
name                       object_id
                           term_id

我想要实现的是,给出一个功能列表,获取包含所有这些功能的所有对象。 我正在尝试这个:

SELECT objects.* 
FROM `object_features` LEFT JOIN `objects` ON ( objects.id=object_features.object_id)
WHERE term_id IN ('1','3','4','10')

这是我正在使用的php代码:

$feature_list = array(1,3,4,10);
$sql = 'SELECT objects.* 
FROM `object_features` LEFT JOIN `objects` ON ( objects.id=object_features.object_id)
WHERE term_id IN ('.implode(',', $feature_list).')';

这接近我的需要,但不同之处在于它返回任何具有任何给定功能的对象,而不是所有功能

3 个答案:

答案 0 :(得分:1)

一个选项是按要从对象返回的数据进行分组,并添加一个计算object.id的having子句,并测试它是否与数组的长度相同。

SELECT objects.id, objects.name 
FROM `object_features` LEFT JOIN `objects` ON ( objects.id=object_features.object_id)
WHERE term_id IN ('1','3','4','10')
group by objects.id,objects.name
having count(objects.id) = 4

不能发誓,因为我最近一直在编写tsql并且没有要测试的mysql实例。

答案 1 :(得分:0)

尝试

'WHERE term_id = '.impode(' AND termid = ', $features_ids).')'

这将导致:

WHERE termid = 1 AND termid = 3 AND termid = 5

<击>

实际上,您需要GROUP BY按每个对象分组,并使用HAVING子句仅允许具有所有termid的行

SELECT objects.* 
FROM `object_features` LEFT JOIN `objects` ON ( objects.id=object_features.object_id)
WHERE term_id IN ('1','3','4','10')
GROUP BY objects.id, objects.name
HAVING count(term_id) = 4

答案 2 :(得分:0)

SQL的做法是:

SELECT objects.* 
  FROM objects
 WHERE null not in 
   ( 
      select of.object_id
        from features f 
        left join object_features of on (f.id = of.id)
   )

假设您有一个包含所有功能的features表。

如果您只需列出某些功能,可以执行(查看子查询的where条件):

SELECT objects.* 
  FROM objects
 WHERE null not in 
   ( 
      select of.object_id
        from features f 
        left join object_features of on (f.id = of.id)
       where f.id in (1,2,3,4,5)
   )