I have two tables, Product and ProductImages.
Product table has 2 columns: ProductID and Name
ProductImages table has 4 columns: ID, ProductID, ImageName and Primary(bit).
The relation between Product and ProductImages is one to many, so one product can have many images, but for each product only one ProductImage will be Primary.
I need to write a query to get all products with their primary images. If the product does not have a primary image, 1st record for the ProductId should be fetched.
Sample product Table
| 1 | P1 |
| 2 | P2 |
| 3 | P3 |
| 4 | P4 |
Sample productImage Table
| 1 | 1 | P1-1 | 1
| 2 | 1 | P1-2 | 0
| 3 | 1 | P1-3 | 0
| 4 | 1 | P1-4 | 0
| 5 | 2 | P2-1 | 1
| 6 | 2 | P2-2 | 0
| 7 | 3 | P3-1 | 0
| 8 | 3 | P3-2 | 0
| 9 | 4 | P4-1 | 0
| 10 | 4 | P4-2 | 0
Output Table
| 1 | 1 | P1-1 | 1
| 5 | 2 | P2-1 | 1
| 7 | 3 | P3-1 | 0
| 9 | 4 | P4-1 | 0
I hope I clarified my question. Please ask if further clarification is required.
You can do this simply like this with
row_number
window function:I assume that primary image
ID
will precede non primary imageID
s.