【问题标题】:insert and join with mysql使用 mysql 插入和加入
【发布时间】:2015-06-02 18:28:08
【问题描述】:

我可以通过连接表将数据插入 MySQL 吗?

我以这种方式创建了我的表,但我无法更改它。 (1.Products。2.照片和产品 ID。3.Photos。)

我在想这样的事情:

INSERT INTO products JOIN photoandproductids 
ON products.productid = photoandproductids.productid 
JOIN photos ON 
photos.photoid=photoandproductids.photoid 
(productname,productcategory,imagepath,imagepath,imagepath,) VALUES 
('test','test','photos/photo1','photos/photo2','photos/photo3')

这个查询有什么问题?

【问题讨论】:

  • 你想做什么?请提供示例数据并解释您要插入的内容。如果一个语句中有多个表,那么答案是“否”。
  • 我正在尝试制作一个管理员表单来插入带有图片的新产品。 (使用 php)
  • 不能同时插入3个表。
  • 分别插入每个表 - 首先是“父母”,然后是“孩子”
  • 你能分享这些表的 DDL 吗?

标签: mysql sql join


【解决方案1】:

没有。这不能在单个 INSERT 语句中完成。将行插入三个表需要三个INSERT 语句。

不清楚你想要达到什么目的。

您可以考虑几个,例如调用一个存储过程来执行您想要执行的多个INSERT 语句。但如果没有规范,我们无法提出任何好的建议。

我们可能假设您使用的是 AUTO_INCREMENT id 列。完成多个插入的一种可能模式是这样的:

 -- repeat this for each product to be inserted

    INSERT INTO products (product_name, product_category) VALUES ('test','test');
    -- if insert is successful, get the value assigned to AUTO_INCREMENT col
    SELECT LAST_INSERT_ID();
    -- save the value returned!


 -- repeat this for each photo to be inserted

    INSERT INTO photo (imagepath) VALUES ('photos/photo1');
    -- if insert is successful, get the value assigned to AUTO_INCREMENT col
    SELECT LAST_INSERT_ID();
    -- save the value returned!
    -- use the saved id values to insert to the linkage table

    -- repeat this for each productid that the photo is associated with
       INSERT INTO photoandproductids (productid, photoid) VALUES (?,?);

如果您不添加产品,则需要运行 SELECT 语句来获取 productid。也就是说,如果 id 在表单中不可用,则从用户选择的下拉列表项中获取。

【讨论】:

  • 这将是一个管理员页面,我们的管理员可以插入带有图片和产品信息的产品。 (尺寸、价格等)。我只有这 3 张桌子,明天我必须完成管理页面。 :(
  • 您使用什么语言和/或框架? Java 春天/休眠?微软ASP? Ruby on Rails?
  • Spencer,我想为最后一个查询自动添加值。可能吗? INSERT INTO photoandproductids (productid, photoid) VALUES (auto,auto); ?这些值将是最后插入的值 + 1。
  • 我正在使用 PHP 和 Mysql 和 HTML
  • @Danny:要实现这一点,您的代码需要在 INSERT 成功完成后立即检索由 INSERT 分配给 AUTO_INCREMENT 列的值(在同一数据库连接中), SELECT LAST_INSERT_ID()。 (执行该查询,并从结果集中获取该行。该行包含先前插入的行的 AUTO_INCREMENT 值,将其保存在变量中,然后您的应用程序可以在 INSERT INTO photoandproductids 语句中提供该值。跨度>
猜你喜欢
  • 2010-10-02
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 2018-03-14
  • 2011-04-14
  • 2011-04-17
  • 2014-03-18
  • 1970-01-01
相关资源
最近更新 更多