在EAV结构化数据模型中搜索实体

时间:2013-03-03 08:11:27

标签: mysql sql entity-attribute-value

我正在尝试在使用实体 - 属性 - 值模型来存储对象的数据库中进行搜索。 有人可以告诉我下面的查询有什么问题吗?

SELECT * FROM object a
   INNER JOIN object_meta b
   ON a.id = b.object 
WHERE
   a.name LIKE '%michael%' AND
   b.name='type' AND b.value='judge'
   AND ( 
      (b.name='country' AND b.value='France') 
      OR  
      (b.name='country' AND b.value='Sweden')
   ) 
ORDER BY a.name DESC
LIMIT 0, 50;

在这种情况下,我想选择名称中包含“michael”且属于判断类型的对象,来自瑞典或法国。我可以看到它在浏览数据库时存在与查询匹配的对象,但在运行查询时没有任何结果。我正在通过命令行运行查询,因此它与应用程序代码无关。

表格结构

object
+----+------------+
| id | name       |
+----+------------+
|  1 | Michael... |
|  2 | Michael... | 
+----+------------+

object_meta
+--------+---------+-----------+
| object | name    | value     |
+--------+---------+-----------+
|   1    | type    | judge     |
|   2    | type    | judge     |
+--------+---------------------+

1 个答案:

答案 0 :(得分:5)

您的查询返回一个空集,因为JOIN中没有可以满足两个条件的行b.name='type' AND b.name='country'

试试这个:

SELECT * FROM object a
   INNER JOIN object_meta b
   ON a.id = b.object 
WHERE
   a.name LIKE '%michael%' AND
   b.name='type' AND b.value='judge'
   AND EXISTS( SELECT 1 FROM object_meta b1 
               WHERE b1.[object]=b.[object] AND ( b1.name='country' AND (b1.value='France' OR b1.value='Sweden'))

   ) 
ORDER BY a.name DESC
LIMIT 0, 50;