查询类似 EVA 的模型
querying on kinda EVA like model
我们有这个 table 和一些数据
在某些情况下,我们需要获取 Entities,它们有一个 属性,具有特殊的 Value 和 属性本身并不重要
可能是我们想要获得的实体具有 属性,其中值等于 1,并且还有一个 属性 的值为 2
简单来说,我们需要这样的东西:
SELECT Entity_Id FROM table WHERE Value = 1 AND Value = 2
此查询 returns 没有,因为 值列 只有 1 个值 ^_^
实际上我们需要这样的东西
SELECT Entity_Id FROM table
GROUP BY Entity_Id
HAVING Value = 1 AND Value = 2
MsSql 不支持此查询,您必须使用聚合函数。 OTL
因为在这种情况下,所有过滤器都设置在 Value 列
你可以将第一个查询解析为这样的东西:
SELECT
DISTINCT Entity_Id,
(SELECT COUNT(*) FROM table WHERE Value = 1 and Order_Id = outerTable.Order_Id)
*
(SELECT COUNT(*) FROM table WHERE Value = 2 and Order_Id = outerTable.Order_Id) as xxx
FROM table AS outerTable
目前我所做的是获取第一个查询谓词并将其解析为第三种形式的查询。
编辑:
在第一次查询时设置的过滤器是可选的,由用户在不知道后台结构的情况下发送,他认为所有属性都保存为该实体的列
这就是为什么我将 AND 解析为
(subQry(filter1) * subQry(filter2) * .... * subQry(过滤器 N))
或
(subQry(filter1) + subQry(filter2) + ..... + subQry(filter N))
寻找更好的解决方案^_^"
提前致谢。
这是一种方法:
SELECT Entity_Id
FROM table
WHERE Value in (1, 2)
GROUP BY Entity_Id
HAVING COUNT(DISTINCT value) = 2;
您可以使用 exists 子句进行检查,像这样:
SELECT Entity_Id
FROM table t1
WHERE Value = 1 AND
exists (
select 1
from table t2
where t1.entity_id = t2.entity_id and
t2.Value = 2)
除了其他答案已经提到的之外,还有另外两种方法:
select entity_id from table where value = 1
intersect
select entity_id from table where value = 2
select t1.entity_id from table t1
join table t2 on t1.entity_id = t2.entity_id
where t1.value = 1 and t2.value = 2
我们有这个 table 和一些数据
在某些情况下,我们需要获取 Entities,它们有一个 属性,具有特殊的 Value 和 属性本身并不重要
可能是我们想要获得的实体具有 属性,其中值等于 1,并且还有一个 属性 的值为 2
简单来说,我们需要这样的东西:
SELECT Entity_Id FROM table WHERE Value = 1 AND Value = 2
此查询 returns 没有,因为 值列 只有 1 个值 ^_^
实际上我们需要这样的东西
SELECT Entity_Id FROM table
GROUP BY Entity_Id
HAVING Value = 1 AND Value = 2
MsSql 不支持此查询,您必须使用聚合函数。 OTL
因为在这种情况下,所有过滤器都设置在 Value 列 你可以将第一个查询解析为这样的东西:
SELECT
DISTINCT Entity_Id,
(SELECT COUNT(*) FROM table WHERE Value = 1 and Order_Id = outerTable.Order_Id)
*
(SELECT COUNT(*) FROM table WHERE Value = 2 and Order_Id = outerTable.Order_Id) as xxx
FROM table AS outerTable
目前我所做的是获取第一个查询谓词并将其解析为第三种形式的查询。
编辑: 在第一次查询时设置的过滤器是可选的,由用户在不知道后台结构的情况下发送,他认为所有属性都保存为该实体的列 这就是为什么我将 AND 解析为
(subQry(filter1) * subQry(filter2) * .... * subQry(过滤器 N))
或
(subQry(filter1) + subQry(filter2) + ..... + subQry(filter N))
寻找更好的解决方案^_^"
提前致谢。
这是一种方法:
SELECT Entity_Id
FROM table
WHERE Value in (1, 2)
GROUP BY Entity_Id
HAVING COUNT(DISTINCT value) = 2;
您可以使用 exists 子句进行检查,像这样:
SELECT Entity_Id
FROM table t1
WHERE Value = 1 AND
exists (
select 1
from table t2
where t1.entity_id = t2.entity_id and
t2.Value = 2)
除了其他答案已经提到的之外,还有另外两种方法:
select entity_id from table where value = 1
intersect
select entity_id from table where value = 2
select t1.entity_id from table t1
join table t2 on t1.entity_id = t2.entity_id
where t1.value = 1 and t2.value = 2