物体
我的尝试:
SELECT o.name
FROM link l
INNER JOIN object o ON o.id = l.o_id
INNER JOIN attr a ON a.id = l.a_id
WHERE a.description = "attr1"
AND a.description = "attr2"
这不会返回任何内容,因为在 JOIN 之后这些是唯一的行。使用 OR 而不是 AND,它会同时返回 obj1 和 obj2。有没有办法在 SQL 内部执行此操作,而不必稍后在代码中进行过滤?我觉得通过 SQL 来完成,因此在数据库中将使我的代码更快。
o.id = 0
SELECT
o.name AS object_name,
a.description AS attribute_description
FROM
object o
JOIN
link l ON o.id = l.o_id
JOIN
attr a ON l.a_id = a.id
WHERE
o.id = 0;
Select o.id, o.name
From object o
Inner join link l ON( l.o_id = o.id )
Group By o.id, o.name
Having Count(Distinct l.a_id) = (Select Count(id) From attr)
请参阅此处的小提琴。
找到一个至少具有所有给定属性的对象您的示例搞砸了,因为您查找“attr1”和“attr2”并希望返回仅具有“attr1”的 obj1。
但是,您想要选择一个对象,因此请从对象表中选择。您想要限制结果,因此请使用 where 子句。无需加入。使用
EXISTS
或
IN
检查对象是否存在所需的属性:
select *
from object
where id in (select o_id from link where a_id = (select id from attr where description = 'attr1')
and id in (select o_id from link where a_id = (select id from attr where description = 'attr2');
与EXISTS
相同:
select *
from object o
where exists (select null from link l where l.o_id = o.id and l.a_id = (select id from attr where description = 'attr1')
and exists (select null from link l where l.o_id = o.id and l.a_id = (select id from attr where description = 'attr2');
SELECT o.name
FROM link l
INNER JOIN object o ON o.id = l.o_id
INNER JOIN attr a ON a.id = l.a_id
WHERE a.description = 'attr1'
OR a.description = 'attr2'
或者更好,你可以使用 IN
SELECT o.name
FROM link l
INNER JOIN object o ON o.id = l.o_id
INNER JOIN attr a ON a.id = l.a_id
WHERE a.description IN ('attr1','attr2');