我有一系列名字:
$names = array('ray'=>0,'bob'=>1,'sue'=>2,'jeff'=>3);
然后我有一个表存储数组中每个关键字之间的关系:
+----------+----------+
| id_a | id_b |
+----------+----------+
| 0 | 1 |
+----------+----------+
| 0 | 2 |
+----------+----------+
| 0 | 3 |
+----------+----------+
| 1 | 2 |
+----------+----------+
| 1 | 3 |
+----------+----------+
| 2 | 3 |
+----------+----------+
目前我存储关系的功能是:
foreach($names as $name=>$id_a){
foreach($names as $n2=>$id_b){
if($name != $n2){
INSERT INTO relationships (id_a,id_b) VALUES ($id_a,$id_b);
}
}
array_shift($names);
}
我想知道是否有更快的SQL解决方案来处理这种类型的操作?
答案 0 :(得分:1)
您可以先构建插入的值数组,然后将其全部插入a single query;那会更快。查询看起来像......
INSERT INTO relationships (id_a, id_b) VALUES (0, 1), (0, 2), (0, 3);