gpt4 book ai didi

sql - 双重过滤具有唯一值和与特定字符串匹配的值的联接表

转载 作者:行者123 更新时间:2023-11-29 14:29:37 25 4
gpt4 key购买 nike

我有两个表:

表:

eventid | elementid |   value
-------------------------------
10 | 1 | 1234
11 | 1 | 5678
12 | 1 | 5678
10 | 2 | true
11 | 2 | true

因此 values 表可以为同一个 elementid 设置多个值。

事件表:

eventid | eventuid
-------------------
10 | abcdef
11 | ghijkg
12 | vwxyz

我的目标是构建一个显示

的查询
value   |   value  |   eventuid
-----------------------------
true | 1234 | abcdef
  • A 列:id 为 1element 的值
  • B 列:ID 为 2element 的值
  • C 列:eventuid

约束:仅在 - 时显示一行

  1. elementid=1valuevalues 表中是唯一的,即没有 eventuid相同 elementid 的相同值 = 1
  2. elementid=2true

我的尝试是先创建一个 View :

create view unique_event as
select distinct e.eventuid, count(v.value)
from events e
join values v on e.eventid = v.eventid
where v.elementid = 1
group by e.eventuid
having count(v.value) = 1;

这似乎无法正常工作,只返回不同的 eventuid - 不知何故它没有过滤掉重复项(如上所述)。

实现既定目标的最佳方式是什么?有没有比单独 View 更好的方法?

最佳答案

一种方法使用存在不存在:

create view unique_event as
select v.eventuid
from values v
where v.elementid = 1 and
not exists (select 1
from values v2
where v2.value = v.value and v2.elementid = 1 and v2.eventuid <> v2.eventuid
) and
exists (select 1
from values v2
where v2.value = 'true' and v2.elementid = 2 and v2.eventuid = v.eventuid
) ;

关于sql - 双重过滤具有唯一值和与特定字符串匹配的值的联接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53651115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com