doutonghang2761 2014-07-18 02:48
浏览 575

MySQL:将多行数据插入表中,一些数据来自另一个表(关系型)

Additional question to MySQL: Insert data into table, some data comes from another table (relational)

My question above basically asked "how can I insert a row into a table, using information found in another row". The answer was to use a query such as:

INSERT INTO user_config(cid, sid, value)
SELECT $cid, id, $value
FROM user_settings
WHERE mid='$mid' AND name='$name'
ON DUPLICATE KEY UPDATE value = $value;

My problem now is, I need to insert multiple rows. For each row I need to insert, there is a different value for $cid, $value, $mid and $name. For example I could run the following (pseudo):

function x($cid, $mid, $name, $value){
    // run query:
    INSERT INTO user_config(cid, sid, value)
    SELECT $cid, id, $value
    FROM user_settings
    WHERE mid='$mid' AND name='$name'
    ON DUPLICATE KEY UPDATE value = $value;
}

x(1,'a','b');
x(2,'c','d');
x(3,'f','e');

Problem is, that would run 3 queries, and I want to be able to do this in one. Is it possible? I could provide an array for $cid, $mid and $name if that helps the problem?

  • 写回答

1条回答 默认 最新

  • dop83362 2014-07-18 09:25
    关注

    Presumably the information in the x calls is expressible as a select on various tables in your database. Your list of x calls looks le a table whose columns are $cid, $mid, $name, $value, right? (Your x calls should have 4 arguments not 3.)

    Give the definitions of the tables and a query that produces the x arguments as a table with columns cid, mid, name, value.

    Then modify the select in your question so that that x select is in the FROM. Of course, you might not have to express the update using a subselect; I am just describing the change in terms of adding syntax to the sytax you gave.

    UPDATE

    You can make a (possibly temporary) table as the x select. Put that table in the FROM. If the table is around while you collecting multiple x argument lists then you can just insert each (cid,mid,name,value) as you get it.

    INSERT INTO user_config (cid, sid, value)
    SELECT cid, id, value
    FROM user_settings s JOIN x
    ON s.mid=x.mid AND s.name=x.name
    ON DUPLICATE KEY UPDATE value = x.value;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分