SQL查询以获取具有相同标识

时间:2016-09-21 14:17:37

标签: sql-server tsql select join

很抱歉,如果这太元素了,但我无法解决。不知道如何在其上搜索信息:

我有三张桌子:

提供商

id_provider  name   
---------- ----------- 
100         John 
101         Sam 
102         Peter   

联系

id_contact  RowNo   Email   
---------- ----------- ---------------- 
100          1      john@work.com
100          2      john@gmail.com
101          1      sam@work.com
101          2      sam@yahoo.com

产品

Id_product  RowNo   Product 
---------- ----------- ------------------------ 
100          1      John’s 1st product
100          2      John’s 2nd product
101          1      Sam’s 1st product
101          2      Sam’s 2nd product
101          3      Sam’s 3rd product

我需要一个查询来显示三个表中的所有数据,如下所示:

Id  name    id_contact  RowNo  Email     Id_Product  RowNo  Product

100  John    100         1  john@work.com    100       1   John’s 1st product
100  John    100         2  john@gmail.com   100       2   John’s 2st product
101  Sam     101         1  sam@work.com     101       1   Sam's 1st product 
101  Sam     101         2  sam@yahoo.com    101       2   Sam's 2nd product
101  Sam     null       null   null          101       3   Sam's 3rd product
102  Peter   null       null   null          null    null  null

我正在尝试我所知道的所有联接,但我无法使其发挥作用。

非常感谢

3 个答案:

答案 0 :(得分:0)

color[] colors = {#ff0000, #00ff00, #0000ff};
color currentColor = colors[0];

void draw() {
  background(currentColor);
}

void mousePressed() {

  color newColor;

  do {
    newColor = colors[int(random(colors.length))];
  } while (newColor == currentColor);

  currentColor = newColor;
}

答案 1 :(得分:0)

SELECT  prov.*,
        c.*,
        prod.*
FROM    PROVIDER prov
        LEFT JOIN Product prod ON prod.id_product = prov.id_provider
        LEFT JOIN Contact c ON prov.id_provider = c.id_contact
                               AND prod.RowNo = c.RowNo

使用左联接但首先将提供者加入产品然后联系

SQL Fiddle Demo

答案 2 :(得分:0)

您可以使用以下查询:

SELECT t1.id_provider AS Id, t1.name, 
       t2.id_contact, t2.cRowNo, t2.Email,
       t2.Id_product, t2.Product
FROM Provider AS t1
LEFT JOIN (
   SELECT COALESCE(id_contact, id_product) AS id,
          c.id_contact, c.RowNo AS cRowNo, c.Email,
          p.Id_product, p.Product, p.RowNo AS pRowNo
   FROM Contact AS c 
   FULL JOIN Product AS p ON p.id_product = c.id_contact AND p.RowNo = c.RowNo
) AS t2 ON t1.id_provider = t2.id

查询在FULL JOINContact表之间执行Product,并加入从FULL JOINProvider表派生的表。

FULL JOIN是必需的,因为我们无法预先知道两个表ContactProduct中的哪一个包含每个id的最多行。