在另一个表中按条件排序的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。我将对其进行测试,然后回复。     
已邀请:
嗯,我想我一开始误解了这个问题。让我再来一点... 如何在产品中添加一个“ user_id \”列来指定哪个用户选择了该列。 如果一个给定的产品只能由一个用户选择,则需要某种方式来知道它已经被选择,以及由谁来选择。我可能会误解您在这里所做的事情,但听起来您正在尝试将产品选择(取决于首选类别,最大利润以及已经选择的内容)与附加步骤结合起来查询结果。您可能需要将此步骤分为两个步骤: 在您的代码中,根据您的条件找出谁获得了哪种产品,并在数据库中将其标记为此类产品。 运行查询以获取结果。 我不知道您是否可以在SQL查询中执行产品选择步骤,除非您将其与一些疯狂的复杂子查询结合使用,即使那样我也不确定是否可行。如果将其分为两步,您的代码将很简单,结果查询也会很简单。     

要回复问题请先登录注册