如果表在SQL Server中具有重复值,如何使用内部联接进行提取

时间:2017-09-19 11:23:26

标签: sql-server

将在sql server中查询内部联接

table1
|---------|------------|-------------|------|
|object_id| object_name|parent_object|type  | 
|---------|------------|-------------|------|
|885      | unique1    |245          |UQ    |
|901      |unique2     |245          |UQ    |
|---------|------------|-------------|------|

 table2
    |---------|------------|-------------|
    |object_id| object_name|is_unique_constraint|
    |---------|------------|-------------|
    |245      | unique1    |1            |
    |245      |unique2     |1            |
    |---------|------------|-------------|

需要输出

|---------|------------|-------------|-------|-------------------|
|object_id| object_name|parent_object|type   |isuniqueconstraint |
|---------|------------|-------------|-------|-------------------|
|885      | unique1    |245          |UQ     |1                  |
|901      |unique2     |245          |UQ     |1                  |
|---------|------------|-------------|-------|-------------------|

在写我的查询时,我得到了重复的结果

SELECT *
FROM table1
INNER JOIN table2 ON table1.parent_object_id = table2.object_id
WHERE type = 'UQ'
    AND is_unique_constraint = 1

1 个答案:

答案 0 :(得分:2)

我认为您只需要在object_name条件中加入join

select . . .
from table1 inner join
     table2
     on table1.parent_object_id = table2.object_id and
        table1.object_name = table2.object_name
where type = 'UQ' and is_unique_constraint = 1;