选择行取决于在其他表MySQL中链接到它的内容

时间:2014-09-16 07:12:07

标签: mysql sql

基本上我只有两张桌子。第一个是"对象"第二个是"属性"。现在我想要具有指定属性的对象。

对象表:

+-----------+
| Column    |
+-----------+
| object_id |
+-----------+

属性表:

+-------------+
| Columns     |
+-------------+
| property_id |
| object_id   |
| key         |
| value       |
+-------------+

现在我选择的是谓词(AND,OR,XOR)的所有对象。

e.g:

property_id object_id key      value
 1           2         name     Mike
 2           2         gender   male
 3           2         hair     blonde
 4           2         married  yes
 5           5         name     John
 6           5         gender   male
 7           5         married  yes
 8           5         job      Cop

假设我想选择性别="男性"和已婚="是"。

您是否有任何想法,如何通过MySQL实现最高效?我的需要是否足够清楚?

Chrispi

4 个答案:

答案 0 :(得分:1)

如果我理解正确,那就像

 Select object_id 
 from objects
 where object_id in (select object_id from properties where gender="male") and 
       object_id in (select object_id from properties where married="yes") ;

仅使用属性的替代方法:

(select object_id from properties where gender="male") 
 intersect
(select object_id from properties where married="yes");

答案 1 :(得分:1)

使用自联接并更好地索引出现在where和join子句

中的列
select t.* from 
test t
join test t1 using(object_id) /* using is short syntax for join you also use on(t.object_id = t1.object_id) */
where t.`key` = 'gender'
and t1.`key` = 'married'
and t.`value` = 'male'
and t1.`value` = 'yes'

Demo

答案 2 :(得分:1)

使用以下语句,您可以获得结果。

(Select object_id from Properties where key = 'married' and value = 'yes')
intersect
(Select object_id from Properties where key = 'gender' and value = 'male')

同样根据您的标准,您可以在上面添加更多条件。

答案 3 :(得分:1)

这在RDBMS中无法有效完成。但是,您可以按照以下方式实现:

SELECT object_id FROM your_table t1 
INNER JOIN your_table t2 ON (
    t1.object_id = t2.object_id 
    AND t2.property_id = 4 
    AND t2.value = 'yes')
WHERE t1.property_id = 6 and t1.value = 'male';