在另一个表中按条件排序的SQLite查询?
|
我有一个SQLite数据库表\'products \',其中包含项目列表,每个项目都有一个类别和一个估计的利润。就像是
|id | product | category_id | profit | customer_id |
|---|----------|--------------|--------|-------------|
| 1 | product1 | 1 | 15 | 0 |
| 2 | product2 | 2 | 10 | 0 |
| 3 | product3 | 1 | 9 | 0 |
| 4 | product4 | 2 | 12 | 0 |
我还有一张“客户”表,可以选择产品,每个选择一个。客户具有他们要从中选择的首选类别和选择顺序:
|id | name | category_id | order |
|---|-------------|--------------|-------|
| 1 | customer1 | 2 | 1 |
| 2 | customer2 | 1 | 2 |
| 3 | customer3 | 1 | 3 |
每种产品都是不同的,因此只有一个其他客户可以选择它,这就是为什么客户订单很重要的原因。我希望根据客户的首选类别和订单来订购产品的清单,假设客户将始终选择该类别中剩余的利润最高的产品。就像是:
|name | product | profit |
|------------|--------------|--------|
|customer1 | product4 | 12 |
|customer2 | product1 | 15 |
|customer3 | product3 | 9 |
我知道我可以加入“类别”列中的表,并且可以按客户订单订购列表,但是我不确定如何强制选择每个产品只能一次选择的约束。
例如
SELECT customers.name, products.name, products.profit
FROM customers INNER JOIN products ON customers.category_id = products.category_id
ORDER BY customers.order, products.profit
请给我列出所有产品的所有客户清单:
|name | product | profit |
|------------|--------------|--------|
|customer1 | product4 | 12 |
|customer1 | product2 | 10 |
|customer2 | product1 | 15 |
|customer2 | product3 | 9 |
|customer3 | product1 | 15 |
|customer3 | product3 | 9 |
您能帮我编写正确的查询吗?
更新:编辑了上表,以结合答案中的一些想法。假设products.customer_id = 0表示未选择产品,我可以编写以下查询。
UPDATE products SET customer_id = customers.id
WHERE products.customer_id = 0 AND products.category_id = customers.category_id
我不希望它能完全按照我的要求运行,因为它还没有解决利润列,而且我不确定该查询如何实际处理wrt customer_id。我将对其进行测试,然后回复。
没有找到相关结果
已邀请:
1 个回复
讹巳漓把备