[英]How do I SELECT only rows from table b that have all the same values for a given column per foreign key?
I have a table that just has ID's.我有一张只有 ID 的表。 Another table that has ID plus a couple other columns.另一个具有 ID 和其他几个列的表。 One such column is [set], for reference.一个这样的专栏是[set],供参考。
I am trying to build a join query on only the ID's in table2 that have the same value for every row in column [set], not just ID'S that have a duplicate value in [set] plus another different value.我正在尝试仅对 table2 中的 ID 构建连接查询,这些 ID 对于列 [set] 中的每一行具有相同的值,而不仅仅是在 [set] 中具有重复值的 ID 加上另一个不同的值。 So, each ID in table2 can have multiple rows.因此,table2 中的每个 ID 都可以有多个行。
table1表格1
[id] [ID] |
---|
a1 a1 |
a2 a2 |
table2表2
[id] [ID] | [op] [操作] | [set] [放] |
---|---|---|
a1 a1 | 22 22 | cut切 |
a1 a1 | 21 21 | cut切 |
a2 a2 | 23 23 | cut切 |
a2 a2 | 25 25 | cut切 |
a2 a2 | 24 24 | slice片 |
In the given example, 'a2' would not fit the criteria because the values in column [set] are not all the same.在给定的示例中,“a2”不符合条件,因为列 [set] 中的值并不完全相同。
My query isn't working.我的查询不起作用。
SELECT DISTINCT(A.ID)
FROM TABLE1 A
INNER JOIN TABLE2 B ON A.ID = B.ID
GROUP BY A.ID, B.SET
HAVING COUNT(DISTINCT(B.SET)) =1
You're grouping by id
and set
, so by definition within each group, there will be just one value for set
.您按id
和set
分组,因此根据每个组中的定义, set
将只有一个值。 Remove it from the group by
clause and you should be OK.从group by
子句中删除它,你应该没问题。 Also, not that since you're grouping by the id
, you don't need a distinct
on it:另外,并不是因为您按id
分组,所以您不需要distinct
:
SELECT A.ID -- Distinct removed. It's not wrong, just redundant
FROM TABLE1 A
INNER JOIN TABLE2 B ON A.ID = B.ID
GROUP BY A.ID -- Grouping by b.set removed
HAVING COUNT(DISTINCT(B.SET)) = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.