du997562 2009-10-22 15:33
浏览 23
已采纳

如果我需要为其他表提取主ID,如何插入

SELECT * FROM tableFoo
LEFT JOIN tableBar ON tableFoo.commonColumn = tableBar.commonColumn
WHERE tableBar.commonColumn IS NULL

Above will select records, I would like to insert Code below will insert id to third table.

INSERT IGNORE INTO jos_mt_links (link_id,link_name,alias)
VALUES(NULL,'tex2','hello');         # generate ID by inserting NULL
INSERT INTO jos_mt_cl (link_id,cat_id)
VALUES(LAST_INSERT_ID(),'88');  # use ID in second table

How do I combine these too? Thx

Again, I add this note here, how do I combine these queries tohether. All of them, including the first query (SELECT *....)

Something like this: SELECT records, then insert them, and also insert this....

  • 写回答

2条回答 默认 最新

  • dongtangu8403 2009-10-22 15:39
    关注

    if you're using php you can just do two querys with mysql_insert_id() in between

    mysql_query("INSERT IGNORE INTO jos_mt_links (link_id,link_name,alias)
    VALUES(NULL,'tex2','hello')");
    $newid=mysql_insert_id();
    mysql_query("INSERT INTO jos_mt_cl (link_id,cat_id)
    VALUES(LAST_INSERT_ID(),'".$newid."')");
    

    re:comment - sorry, total missed that, so you need to run 3 queries

    $result=mysql_query("SELECT * FROM tableFoo LEFT JOIN tableBar ON tableFoo.commonColumn = tableBar.commonColumn WHERE tableBar.commonColumn IS NULL");
    $row=mysql_fetch_assoc($result);
    mysql_query("INSERT IGNORE INTO jos_mt_links (link_id,link_name,alias)
        VALUES(NULL,'".$row['linkfield']."','".$row['aliasfield']."')");
    mysql_query("INSERT INTO jos_mt_cl (link_id,cat_id)
        VALUES(LAST_INSERT_ID(),'".$row['catidfield']."')");
    

    i don't know what are the names of your fields in tableFoo and tableBar, so just replace linkfield/aliasfield/catidfield with those names.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制