【问题标题】:Inserting new values combined with a select query using prepared statements使用准备好的语句插入与选择查询相结合的新值
【发布时间】:2013-08-24 06:17:31
【问题描述】:

使用准备好的语句插入新值并结合选择查询的正确语法是什么?

我所拥有的不起作用。

INSERT INTO productsUsers
    (product, userId)
VALUES
    (?, SELECT id FROM users WHERE username = ?)

【问题讨论】:

    标签: mysql select insert


    【解决方案1】:

    只需使用INSERT INTO...SELECT:

    INSERT INTO productsUsers (product, userId)
    SELECT ?,  id 
      FROM users 
     WHERE username = ?;
    

    如果您想避免重复的id,您可以使用ON DUPLICATE KEY 子句。查看the documentation 了解更多信息。

    【讨论】:

      【解决方案2】:

      试试这个:-

      INSERT INTO productsUsers(product, userId)
      SELECT ?,  id 
        FROM users 
        WHERE username = ?)
      

      查看reference

      语法是:-

      插入 [LOW_PRIORITY | HIGH_PRIORITY] [忽略]

      [INTO] tbl_name [(col_name,...)]
      SELECT ...
      [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
      

      【讨论】:

        猜你喜欢
        • 2015-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-02
        • 2020-10-27
        • 1970-01-01
        • 2016-09-16
        • 1970-01-01
        相关资源
        最近更新 更多