简体   繁体   English

MySQL,使用其他表中的数据创建表

[英]MySQL,Create table using data from other tables

Could you help me with designing a MySQL query for creating a table with data from other 3 tables?你能帮我设计一个 MySQL 查询来创建一个包含来自其他 3 个表的数据的表吗?

Database design:数据库设计:

在此处输入图片说明

What I have tried was:我尝试过的是:

INSERT INTO SklepZaloha (TIME)
    SELECT TIME FROM Item1;
INSERT INTO SklepZaloha (Boiler)
    SELECT Value FROM Item1;
INSERT INTO SklepZaloha (Zpatecka)
    SELECT Value FROM Item2;
INSERT INTO SklepZaloha (Vymnenik)
    SELECT Value FROM Item3;

But that results in: aaabbbccc instead of: abcabcabc但这会导致:aaabbbccc 而不是:abcabcabc

Your INSERT ... SELECT needs to insert the entire row at once, not nibble away one value at a time.您的INSERT ... SELECT需要一次插入整行,而不是一次蚕食一个值。 To do this, you need to use a JOIN .为此,您需要使用JOIN

INSERT INTO SklepZaloha
    (`Time`, Boiler, Zpatecka, Vymnenik)
  SELECT i1.`Time`, i1.Value, i2.Value, i3.Value
    FROM Item1 i1
    INNER JOIN Item2 i2
      ON i1.`Time` = i2.`Time`
    INNER JOIN Item3 i3
      ON i1.`Time` = i3.`Time`;

The SELECT portion would also be the correct syntax for a SELECT ... INTO OUTFILE query. SELECT部分也是SELECT ... INTO OUTFILE查询的正确语法。

I can tell you one thing, you're going to have to use a prepared statement in a stored procedure in all likelihood.我可以告诉你一件事,你很可能必须在存储过程中使用准备好的语句。 It's been some time since I've done this, but within a stored procedure you can access the tables with the data and then construct a prepared statement that you then execute.我已经有一段时间没有这样做了,但是在存储过程中,您可以访问包含数据的表,然后构造一个准备好的语句,然后执行该语句。

The MySQL documentation on stored procedures as well as prepared statements is pretty good.关于存储过程和准备好的语句的 MySQL 文档非常好。

I do vaguely remember, however, there being an issue with executing statements of this type in a stored procedure.但是,我依稀记得,在存储过程中执行这种类型的语句存在问题。

Sorry I can't be more helpful.抱歉,我帮不上忙了。

Michael迈克尔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM