sqldatabaseinner-joinmulti-query

How to get data with multiple references to single table


I have Image table with 3 columns: Id, Name, and RefId - It will contain Id from other table (with this example is Category table and Product table). Category table with 3 columns: Id, Name and ProductId. Product table includes 3 columns: Id, Name. This is Product's data:

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

And Category's data:

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

Image's data:

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

Please see this data for the example: Image1 is the image of the product and Image2 is the image of the category. And my query:

    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 

With this query only get Image2 or Image1. My problem is how to get 2 Image with only one query?


Solution

  • Are you looking for something like this?

    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 
    

    Output:

    |                          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 |
    

    Here is SQLFiddle demo