3

可以说我有以下表格:

  • 顾客
  • 产品
  • 客户产品

有没有办法从客户和产品表中进行选择,其中值不在映射表中?基本上我需要一份他们不拥有的客户和产品的匹配列表。

另一个转折点:我需要为每个产品配对一个客户。所以如果 5 个客户没有产品 A,那么只有查询中的第一个客户应该有产品 A。所以结果看起来像这样:

(假设所有客户都拥有产品 B,并且不止一个客户拥有产品 A、C 和 D)

  1. 客户 1,产品 A
  2. 客户 2,产品 C
  3. 客户 3,产品 D

最后的转折:我需要将此查询作为 SQL Sever 中 UPDATE 语句的一部分运行。所以我需要从第一行取值:

客户 1,产品 A

并将客户记录更新为类似

UPDATE Customers
SET Customers.UnownedProduct = ProductA
WHERE Customers.CustomerID = Customer1ID

但如果我能在一个 SQL 语句中完成整个过程,那就太好了。所以我运行了一次查询,它用他们不拥有的产品更新了 1 个客户。希望这不会让您感到困惑!提前致谢!

4

4 回答 4

3
WITH q AS
        (
        SELECT  c.*, p.id AS Unowned,
                ROW_NUMBER() OVER (PARTITION BY p.id ORDER BY c.id) AS rn
        FROM    Customers c
        CROSS JOIN
                Products p
        LEFT JOIN 
                CustomerProducts cp
        ON      cp.customer = c.id
                AND cp.product = p.id
        WHERE   cp.customer IS NULL
        )
UPDATE  q
SET     UnownedProduct = Unowned
WHERE   rn = 1

UPDATE声明将更新第一个不拥有特定产品的客户。

如果要选择列表,则需要:

SELECT  *
FROM    (
        SELECT  c.*, p.id AS Unowned,
                ROW_NUMBER() OVER (PARTITION BY p.id ORDER BY c.id) AS rn
        FROM    Customers c
        CROSS JOIN
                Products p
        LEFT JOIN 
                CustomerProducts cp
        ON      cp.customer = c.id
                AND cp.product = p.id
        WHERE   cp.customer IS NULL
    ) cpo
WHERE   rn = 1
于 2009-03-18T15:22:39.443 回答
0

如果您一次只更新一个客户,您可能需要记住哪些产品是自动分配的(在 CustomerProducts 中)或有一个计数器自动分配产品的频率(在 Products 中)

于 2009-03-18T15:23:00.533 回答
0

我在 oracle 中试过这个(希望它也适用于你)

UPDATE customers c
   SET unownedProduct =
       ( SELECT MIN( productid )
           FROM products
          WHERE productid NOT IN (
              SELECT unownedProduct
                FROM customers
               WHERE unownedProduct IS NOT NULL )
            AND productid NOT IN (
              SELECT productid
                FROM customerProducts cp
               WHERE cp.customerId = c.customerid )
       )
 WHERE customerId = 1
于 2009-03-18T16:25:35.127 回答
0

What if the customer doesn't own more than one product? and how are you going to maintain this field as the data changes? I thinkyou really need to do some more thinking about your data structure as it doesn't make sense to store this information in the customer table.

于 2009-03-18T17:29:12.070 回答