如何获取具有对单个表的多个引用的数据

时间:2013-07-18 08:13:14

标签: sql database inner-join multi-query

我的Image表包含3列:IdNameRefId - 它将包含来自其他表的Id(此示例为Category表和Product表)。 Category表包含3列:IdNameProductIdProduct表包含3列:IdName。 这是产品的数据:

Id                                     Name    
659543D6-1A0D-4151-B94C-F44CCDA752B5   Product1
5C1A5A2F-4579-41D2-8FAE-93EF71451285   Product2     
2C35A651-1681-4E5E-9F0C-315169BDFA1D   Product3

Category的数据:

Id                                     Name        ProductId     
F3FFF612-1D6D-4447-B472-2486C4893CDD   Category1   659543D6-1A0D-4151-B94C-F44CCDA752B5
4A2FF39D-13E0-4365-8DEA-7FAD6D6DF405   Category2   659543D6-1A0D-4151-B94C-F44CCDA752B5
599AEA59-8A85-409C-9026-7E4313AF523D   Category3   659543D6-1A0D-4151-B94C-F44CCDA752B5

图片数据:

Id                                     Name     RefId     
BDD396A2-37A7-4B20-B8C5-8EF2CD58D4C0   Image1   659543D6-1A0D-4151-B94C-F44CCDA752B5
7CDA01FF-B98A-4CDC-A92B-0E31A9CDCD20   Image2   F3FFF612-1D6D-4447-B472-2486C4893CDD

请参阅此数据以获取示例: Image1 是产品的图像, Image2 是该类别的图像。我的问题是:

    SELECT Category.Id, Category.Name, Product.Name, Image.Name 
    FROM Category 
    INNER JOIN Product
    ON Category.ProductId = Product.Id
    INNER JOIN Image
    ON Category.Id = Image.RefId
 -- ON Product.Id = Image.RefId 

使用此查询只能获取 Image2 Image1 。我的问题是如何只用一个查询获得2个图像?

2 个答案:

答案 0 :(得分:2)

SELECT Category.Id, Category.Name, Product.Name, I1.Name, I2.Name
  FROM Category 
  INNER JOIN Product
  ON Category.ProductId = Product.Id
  LEFT OUTER JOIN Image I1
  ON Category.Id = I1.RefId
  LEFT OUTER JOIN Image I2
  ON Product.Id = I2.RefId

答案 1 :(得分:1)

你在找这样的东西吗?

SELECT c.Id category_id, 
       c.Name category_name, 
       p.Name product_name, 
       i1.Name category_image, 
       i2.Name product_image
  FROM Category c JOIN Product p
    ON c.ProductId = p.Id LEFT JOIN Image i1 
    ON c.Id = i1.RefId LEFT JOIN Image i2
    ON p.Id = i2.RefId 

输出:

|                          CATEGORY_ID | CATEGORY_NAME | PRODUCT_NAME | CATEGORY_IMAGE | PRODUCT_IMAGE |
--------------------------------------------------------------------------------------------------------
| F3FFF612-1D6D-4447-B472-2486C4893CDD |     Category1 |     Product1 |         Image2 |        Image1 |
| 4A2FF39D-13E0-4365-8DEA-7FAD6D6DF405 |     Category2 |     Product1 |         (null) |        Image1 |
| 599AEA59-8A85-409C-9026-7E4313AF523D |     Category3 |     Product1 |         (null) |        Image1 |

这是 SQLFiddle 演示