drcb19700 2010-11-09 17:32
浏览 30

PHP和Mysqli - 多个查询合二为一?

I need to get the ID (a column) from the last row inserted, in a table. I'm wondering if there's any way to somehow embed that in another query, to avoid having two different querys? It seems much simpler, and i believe i've seen it somewhere before.

Something like this:

$query = "INSERT INTO a_table (x, y) VALUES ((SELECT id FROM another_table ORDER BY id DESC), 'y...')";

Any ideas how to do that? Thanks.

  • 写回答

3条回答 默认 最新

  • douben7260 2010-11-09 17:35
    关注

    If you're looking to get the newest record created by your script, you should never do it this way in the first place. What if another instance of your script created a record at the same time?

    mySQL's LAST_INSERT_ID() will return the last ID created over this specific connection. However, you must call it immediately after your insert statement.

    If getting the highest ID is literally what you want, GSto's answer will work for you.

    评论

报告相同问题?

悬赏问题

  • ¥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 库的使用