Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 使用不重复的值联接两个表_Sql Server 2008 - Fatal编程技术网

Sql server 2008 使用不重复的值联接两个表

Sql server 2008 使用不重复的值联接两个表,sql-server-2008,Sql Server 2008,我有两张桌子 表 表B id desc uni 1 kfgh asad 1 oiuy asad 1 wert asad 3 wewe sfds 4 lkjh qwer 4 poiu qwer 现在我想加入这两个表 在尝试内部联接时获取列uni中的值 SELECT uni FROM tableA as A JOIN tableB as B ON A.id = B.id 它给出了

我有两张桌子 表

表B

id    desc    uni
1     kfgh    asad
1     oiuy    asad
1     wert    asad
3     wewe    sfds
4     lkjh    qwer
4     poiu    qwer
现在我想加入这两个表 在尝试内部联接时获取列
uni
中的值

SELECT     uni FROM      tableA as A JOIN tableB as B  ON  A.id = B.id

它给出了TableB中的所有行。正如您三次注意到的id为1的行。我不能在这里使用distinct,因为这是大型查询的一小部分,此join语句将影响整个查询。有人能告诉我需要尝试哪种联接吗。

使用子查询来获得所需的不同位

SELECT DISTINCT id, uni FROM tableb
所以

编辑 如果您想要表a中的所有行,则需要使用左联接

SELECT     
  a.id, 
  b.uni 
FROM
   tableA as A 
LEFT JOIN (
       SELECT DISTINCT id, uni FROM tableb
     ) as B  
ON  A.id = B.id

你的桌子好像不太舒服。特别是,他们似乎违反了法律

要解决此问题,您应该将表结构更改为以下内容:

表a

id    name
1     asd
2     afg
3     qwe
4     dsf
表格Unis

id    uni
1     asad
3     sfds
4     qwer  
id    desc
1     kfgh
1     oiuy
1     wert
3     wewe
4     lkjh
4     poiu
表格说明

id    uni
1     asad
3     sfds
4     qwer  
id    desc
1     kfgh
1     oiuy
1     wert
3     wewe
4     lkjh
4     poiu
并使用此查询:

SELECT unis.uni FROM tableA AS A JOIN tableUnis AS unis ON A.id = unis.id

字段“uni”的内容是否直接依赖于字段“id”?如果是的话,你可能想考虑把这个关系移到它自己的表中。你不能只在子查询中使用区别吗?@ HaukeP。fild“uni”直接依赖于字段“id”。但我不理解您的建议。请将其添加为anserI,并同意您的规范化。您的查询工作正常,但它不会返回id=2的行。由于这是大型查询的一部分,我不能将这一行留在这里,请修改您的问题以显示您期望的输出-我没有看到与id=2对应的uni