doucai1901 2015-01-07 23:25
浏览 11
已采纳

基于现有行的受控表查询

I have a product_group table with the following fields: group_id, product_id, order. The table will be queried against a lot: a single-form view will make it possible to insert new records and/or update existing ones with one submit.

I'm trying to figure out optimal solution to cover the following 3 cases:

  1. User tries to insert an existing row: do nothing. Here a unique index of the 3 columns can be useful.

  2. User changes only the order column: perform an update.

  3. User inserts a completely new set of values: perform an insert.

Is there a way to put all of this together in one MySQL query? If not, what would be the best approach here? The goal is to limit database queries as much as possible.

  • 写回答

1条回答 默认 最新

  • dongmeng4742 2015-01-08 00:09
    关注

    Does this do what you want?

    insert into product_group(group_id, product_id, `order`)
        values (@group_id, @product_id, @order)
        on duplicate key update `order` = values(`order`);
    

    Along with a unique index on group_id, product_id:

    create unique index idx_product_group_2 on product_group(group_id, product_id)
    

    This handles your three cases:

    1. Because the value assignment is a no-op if the values are the same.
    2. The order column will be updated if the other two have the same value.
    3. A new row that has a different group_id or product_id will be inserted.

    As a note, order is a lousy name for a column, because it is a SQL key word.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用