我有一個與Entity2具有一對多關係的Entity1。 實體2存儲屬性並具有「鍵」和「值」字段。一對多查詢元組
現在我需要查詢所有ENTITY1的具有一定的鍵/值組合(與邏輯)
SELECT e1 FROM Entity1 e Join e.props e2
WHERE
e2.key = :key1 and e2.value = :value1
And
e2.key = :key2 and e2.value = :value2 -- wont work
我有一個與Entity2具有一對多關係的Entity1。 實體2存儲屬性並具有「鍵」和「值」字段。一對多查詢元組
現在我需要查詢所有ENTITY1的具有一定的鍵/值組合(與邏輯)
SELECT e1 FROM Entity1 e Join e.props e2
WHERE
e2.key = :key1 and e2.value = :value1
And
e2.key = :key2 and e2.value = :value2 -- wont work
select e1.*
from entity1 e1
join entity2 e21 on e21.e1_id = e1.id and e21.key = :key1 and e21.value = :value1
join entity2 e22 on e22.e1_id = e1.id and e22.key = :key2 and e22.value = :value2
我想這是一個本地SQL查詢。 這是一個合適的JPQL查詢的作品。 SELECT E1 FROM EsbErrorEntity爲E1 加入e1.props E21 加入e1.props E22 WHERE e21.headerKey =:KEY1和e21.headerValue =:數值 和e22.headerKey =:鍵2和e21.headerValue =:VALUE2 – user3092750 2014-12-05 13:58:45
使用此,很容易推廣到更多的關鍵
SELECT some_filed FROM Entity1 AS e1 Join e1.props AS p
WHERE
(p.key = :key1 and p.value = :value1)
and
(p.key = :key2 and p.value = :value2);
你看,這個查詢不會返回key1 <> key2的任何東西,這通常是這種情況。 – 2014-12-05 12:06:14
@Dmitry:我只是試圖糾正語法而不是邏輯。我的查詢是錯誤的嗎? – 2014-12-05 12:11:22
我想是的,即使從語法的角度來看...... [內部] JOIN語句應該包含ON子句:) – 2014-12-05 12:44:54
單程/值對使用條件聚合:
SELECT entity_id
FROM e.props
GROUP BY entity_id
HAVING SUM(CASE WHEN e2.key = :key1 and e2.value = :value1 THEN 1 ELSE 0 END) > 0 AND
SUM(CASE WHEN e2.key = :key2 and e2.value = :value2 THEN 1 ELSE 0 END) > 0;
有關更多條件,您可以在having
中添加更多條款。
JPA理解存在:
SELECT e1 FROM Entity1 e1
WHERE exists (select 1 from Entity2 e2
where e2.entity1.id = e1.id
and e2.key = :key1 and e2.value = :value1)
AND exists (select 1 from Entity2 e2
where e2.entity1.id = e1.id
and e2.key = :key2 and e2.value = :value2);
也許 「e2.key =:KEY1和e2.value =:數值或e2.key =:鍵2和e2.value =:VALUE2」? – Multisync 2014-12-05 11:06:03
@Multisync,它不會檢查屬性的_combination_。 – 2014-12-05 11:29:12