简体   繁体   English

SQL 加入并获取所有符合条件的

[英]SQL Join and get all that match a condition

I have two tables like this:我有两个这样的表:

Table1表格1

Col1 Col1 Col2 Col2
A一个 X X
B X X
C C X X
A一个 Y
B Z Z

Table2表2

Col3 Col3 Col4 Col4
X X true真的
Y false错误的
Z Z true真的

How can I write a SQL query such that I get the Col1 values where that row only has a Col2 join with table 2 which have a col 4 that is true and must not contain a false value.如何编写 SQL 查询,以便获得 Col1 值,其中该行仅具有与表 2 的 Col2 连接,表 2 的 col 4 为真且不得包含假值。

So for the example tables, the values returned would be B and C.因此,对于示例表,返回的值将是 B 和 C。 A would not be returned as the join to Table 2 for row Y would be false. A 不会被返回,因为对表 2 的行 Y 的连接将是错误的。

So this query needs to get the unique list of values in Col1, then from that join table1 and table2 on Col2, and then from the unique list, get those which only have a true value on this joined table.所以这个查询需要获取 Col1 中的唯一值列表,然后从 Col2 上的连接 table1 和 table2 中,然后从唯一列表中,获取在这个连接表上只有真实值的那些。

You can join the tables and use aggregation with the condition in the HAVING clause:您可以连接表并将聚合与HAVING子句中的条件一起使用:

SELECT t1.Col1
FROM Table1 t1 INNER JOIN Table2 t2
ON t2.Col3 = t1.Col2
GROUP BY t1.Col1
HAVING MIN(t2.Col4) = true; -- just HAVING MIN(t2.Col4) would also work

If the min value of Col4 for a specific Col1 is true which is interpreted as 1, this means that there is no false which is interpreted as 0.如果特定Col1Col4的最小值为true (被解释为 1),这意味着不存在被解释为 0 的false

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM