I have a table of products and another table of specific listings of these products.
CREATE TABLE products (id INT AUTOINCREMENT);
CREATE TABLE listings (
id INT AUTOINCREMENT,
product INT REFERENCES products(id),
vendor INT
)
I want to select listings for a set of products in such way that they are sold by minimal count of different vendors. As an example:
id | product | vendor |
---|---|---|
1 | 1 | 1 |
2 | 1 | 2 |
3 | 2 | 3 |
4 | 2 | 1 |
5 | 3 | 4 |
For products (1,2,3)
I expect to get ids (1,4,5)
. Is there a way to achieve this just using SQL? Or should I simply use multiple queries and combine the results elsewhere?
2
Answers
You can achieve this using SQL by writing a query that selects the listings for the specified products in a way that minimizes the count of different vendors. Here’s a SQL query that should give you the desired result:
In query, the common table expression (CTE) named RankedListings is utilized to rank listings by counting different vendors for the same product and assign a rank using the ROW_NUMBER() function. This CTE involves a self-join on the listings table to determine the number of unique vendors selling the same product. The results are filtered to include only specified products (1, 2, 3). In the main query, it selects listing IDs from the RankedListings CTE with a row number of 1, effectively identifying listings sold by the fewest different vendors for each product, achieving the desired outcome
Use a recursive query to get all possible combinations. In your case IDs (1,3,5), (1,4,5), (2,3,5) and (2,4,5). Then check the distinct number of vendors per set, take the one with the lowest number of vendors and show the rows.
Here are my steps:
The query:
Demo: https://dbfiddle.uk/uMqMs0xn