如何将另外的值插入到另一个表中,因为它是在另一个表的特定列中定义的

时间:2013-12-30 11:36:24

标签: mysql postgresql

我有两张表,Movements和sales

动作(示例)

clock_model| piece_ref| original_stock |
-----------+----------+-----------------
R0000000000| 0000ZZZ  |       5        |

销售(我只是向您展示结构)

id_sale (autoincrement numeric value)
piece_ref
pieces_to_sent 
type_of_sale
customer
lastupdate_date
lastupdate_by

我想知道哪个查询应该是正确的,以便将尽可能多的piece_ref插入到sales表中,因为它的结果将类似于上面的示例:

销售

id_sale| piece_ref|  pieces_to_sent | type_of_sale | customer | lastupdate_date
-------+----------+-----------------+--------------+----------+-----------------
1      | 0000ZZZ  |       0         |  "none"      | "no one" |      NOW()
2      | 0000ZZZ  |       0         |  "none"      | "no one" |      NOW()
3      | 0000ZZZ  |       0         |  "none"      | "no one" |      NOW()
4      | 0000ZZZ  |       0         |  "none"      | "no one" |      NOW()
5      | 0000ZZZ  |       0         |  "none"      | "no one" |      NOW()  

我认为postgresql查询会是这样的:

INSERT INTO `Sales` (`piece_ref`, `pieces_to_sent `, 
`type_of_sale`, `customer`,`lastupdate_date`)

SELECT `Movements`.`piece_ref`, 0, "", "", NOW(), "admin"  
FROM   `Movements`, generate_series(1, `Movements`.original_stock) AS rn

但是你知道MySQL中不存在generate_series函数。你能帮我个忙吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

下面的代码是对mysql的引用。

$mydata = mysql_query("SELECT `piece_ref`,`original_stock` FROM `Movements`");
if(mysql_row_nums($mydata)>0){
    while($row = mysql_fetch_assoc($mydata)){
         for($i=0;$i<(int)$row['original_stock'];$i++){
             mysql_query("INSERT INTO `Sales` (`piece_ref`, `pieces_to_sent `, `type_of_sale`, `customer`,`lastupdate_date`) values('".$row['piece_ref']."',0,'','','".date('Y-m-d H:i:s')."')");
         }
    }
} 

答案 1 :(得分:0)

创建一个数字从1到N的辅助表
(其中N是您希望插入的最大件数)。

例如:

CREATE TABLE numbers( x int primary key auto_increment );

INSERT INTO numbers
SELECT null FROM information_schema.columns
LIMIT 100;

此表可用于以下查询以生成必要的记录:

SELECT '0000ZZZ', 0,'none','no one',NOW()
FROM movements m
JOIN numbers n
ON n.x <= m.original_stock

然后将它们插入表中:

INSERT INTO sales( piece_ref, pieces_to_sent, type_of_sale, 
                   customer, lastupdate_date )
SELECT '0000ZZZ', 0,'none','no one',NOW()
FROM movements m
JOIN numbers n
ON n.x <= m.original_stock

演示 - &gt; http://www.sqlfiddle.com/#!9/cc299/1


EDIT点。

上面的查询是针对MySql的,在PostGreSql中,不需要带有数字的表,而是使用generate_series函数:

INSERT INTO sales( piece_ref, pieces_to_sent, type_of_sale, customer, lastupdate_date )
select '0000ZZZ', 0,'none','no one',NOW()
from generate_series(1,(SELECT max(original_stock) FROM movements) ) x
join movements m
on x <= m.original_stock;

演示:http://www.sqlfiddle.com/#!12/3720c/1