sql-从外部表赋值

guicsvcw  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(269)

我有一个两列的表格,上面有客户的ID和优惠券。我想通过将外部数据列表中的凭证分配给每个客户的id来填写“优惠券”列。此外,一旦分配了代码,就不能再次将其分配给其他客户。
你能帮我写一个sql查询吗?

Table:
| Customer ID | Coupon |
| -------- | -------------- |
| 100  |            |
| 200  |           |
| 300 |           |

Data list:
| Voucher ID | Voucher |
| -------- | -------------- |
| 1   |      j2h3h2      |
| 2  |      hfd7s8     |
| 3  |    fsdfs72       |

Final result
| Customer ID | Coupon |
| -------- | -------------- |
| 100   |      j2h3h2      |
| 200  |      hfd7s8     |
| 300  |    fsdfs72       |
kx7yvsdv

kx7yvsdv1#

正如您所评论的,您正在使用mysql 8,我将使用公共表表达式和 ROW_NUMBER() 创建按顺序编号的行。
然后,我可以将它们连接回正在更新的表,并相互连接,以便将新的凭证id分配给没有凭证id的客户。
我也会用这个词 voucher ,因为您似乎互换使用了代金券和优惠券。

WITH
  renumbered_customer AS
(
  -- Find all rows in the customer table that do Not have an assigned voucher
  -- Number those rows sequentially from 1 upwards
  SELECT
    *,
    ROW_NUMBER() OVER (ORDER BY customer_id)   AS row_id
  FROM
    customer
  WHERE
    voucher_id IS NULL
),
  renumbered_voucher AS
(
  -- Find all rows in the voucher table that have not bee assigned to a customer
  -- Number those rows sequentially from 1 upwards
  SELECT
    *,
    ROW_NUMBER() OVER (ORDER BY voucher_id)   AS row_id
  FROM
    voucher
  WHERE
    NOT EXISTS (
      SELECT *
        FROM customer
       WHERE customer.voucher_id = voucher.voucher_id
    )
)
UPDATE
  customer
INNER JOIN
  renumbered_customer  c
    ON c.customer_id = customer.customer_id
INNER JOIN
  renumbered_voucher   v
    ON c.row_id = v.row_id
SET
  customer.voucher_id = v.voucher_id
;

工作演示:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=29875e64b3de3559ceea20d85d222f9b

相关问题