【问题标题】:Insert data into joined tables [duplicate]将数据插入连接表[重复]
【发布时间】:2018-05-09 05:31:40
【问题描述】:

我可以选择和加入,但我不能同时插入这些下表。如何向联接表中插入数据?

  • company(cid, comp_name)

  • role(rid, role_name)

  • user(uid, user_name, cid, rid)

cid,riduid 是自动递增的主键。

我想接受来自前端应用程序的user_name,comp_name,role_name 并在用户表中输入用户名和对应的cidrid。加入后我可以从用户表中获取数据,但我不知道如何插入。

我已经写了一个查询:

INSERT INTO user ( user_name, cid, rid)
SELECT c.cid, r.rid FROM company c
    JOIN user u
    join role r ON c.cid = u.cid and r.rid=;

请帮忙。提前致谢

【问题讨论】:

    标签: mysql


    【解决方案1】:

    如果你想同时插入三个不同的表。您必须进行三个不同的查询。

    示例:

    INSERT INTO user ( user_name, cid, rid) values (/*Variables for user_name, cid, rid*/)
    INSERT INTO company( cid, comp_name) values (/*Variables for cid, comp_name. cid must have been same as cid above then store it in a variable and use it everywhere*/)
    INSERT INTO role( rid, role_name) values (/*Variables for role*/)
    

    如果不是您想要的,请清楚地解释您的问题。

    或者你可以使用 Scop_Identity() IE "插入 tbl1 值 (@name、@age、@address)

    插入 tbl2 值 (scope_identity(), @roleid)"

    【讨论】:

      猜你喜欢
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 2019-07-01
      • 2014-12-04
      相关资源
      最近更新 更多