gpt4 book ai didi

sql - 如何从一个表中选择一个值,其中在另一个表中满足两个单独的条件对

转载 作者:行者123 更新时间:2023-12-03 06:54:01 25 4
gpt4 key购买 nike

如果这是一个不好的问题,我很抱歉。我是 SQL 新手,自己无法找到答案。

我有两张 table 。第一个表包含一个 id 和唯一的单词。第二个表包含一个 id、property_name 和 property_value,并且每个单词可以有多个属性。


+----+------+
| id | word |
+----+------+
| 1 | dog |
| 2 | tree |
| 3 | dang |
| 4 | frog |
+----+------+

房产
+----+---------------+----------------+
| id | property_name | property_value |
+----+---------------+----------------+
| 1 | letters | 3 |
| 1 | first_letter | d |
| 2 | letters | 4 |
| 2 | first_letter | t |
| 3 | letters | 4 |
| 3 | first_letter | d |
| 4 | letters | 4 |
| 4 | first_letter | f |
+----+---------------+----------------+

我想选择一个满足两组条件的单词。下面是我想要实现的伪代码。
SELECT word
WHERE
1) (property_name = 'letters' and property_value = '3')
2) (property_name = 'first_letter' and property_value = 'd')

首先,我在 google 上搜索了将一个表连接到另一个表的示例,其中第一个表中的每个值都可以存在多个属性。我在描述我正在搜索的内容时遇到了很多困难,并且无法在谷歌上找到任何内容。我还在堆栈溢出中搜索了类似的问题,但问题只是模糊相似,答案对我不起作用。总之,这是我连续第三天试图找到这个解决方案。

以下是我的一些尝试:

我试过嵌套一个 and 语句。
SELECT w.word
FROM word w
LEFT JOIN property p ON (w.id = p.id)
WHERE ((p.property_name = 'letters' and p.property_value = '3') and
(p.property_name = 'first_letter' and p.property_value = 'd'))
GROUP BY w.word

我还尝试了多个左连接。
SELECT w.word
FROM word w
LEFT JOIN property p ON (w.id = p.id)
WHERE (p.property_name = 'letters' and p.property_value = '3')
LEFT JOIN property p ON (w.id = p.id)
WHERE (p.property_name = 'first_letter' and p.property_value = 'd')
GROUP BY w.word

上面的第一次尝试返回一个只满足第一个条件的连接表。第二次尝试返回语法错误。

还有更多失败的尝试,但为简洁起见,我没有包括它们。

对于我上面写的伪代码,我想要的结果是:
dog

我只是不知道如何编写执行此操作的查询。

最佳答案

通过使用 INTERSECT,您可以编写一个高效、直观且实际上与您最初编写的非常相似的查询:

SELECT word FROM words
WHERE id IN (
SELECT id FROM properties WHERE property_name = 'letters' AND property_value = '3'
INTERSECT
SELECT id FROM properties WHERE property_name = 'first_letter' AND property_value = 'd'
);

关于sql - 如何从一个表中选择一个值,其中在另一个表中满足两个单独的条件对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58533390/

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