简体   繁体   English

在数组SQL查询中的所有元素之间创建关系。

[英]Create Relationship Between All Elements in an Array SQL query.

I've got an array of names: 我有一系列名称:

 $names = array('ray'=>0,'bob'=>1,'sue'=>2,'jeff'=>3);

Then I have a table that stores relationships between each keyword in the array: 然后,我有了一个表,用于存储数组中每个关键字之间的关系:

+----------+----------+
|  id_a    |   id_b   |
+----------+----------+
|   0      |    1     |
+----------+----------+
|   0      |    2     |
+----------+----------+
|   0      |    3     |
+----------+----------+
|   1      |    2     |
+----------+----------+
|   1      |    3     |
+----------+----------+
|   2      |    3     |
+----------+----------+

At the moment my function to store the relationships is: 目前,我存储关系的功能是:

    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);
    }

I'm wondering if there is a faster SQL solution to handle this type of action? 我想知道是否有更快的SQL解决方案来处理此类操作?

You can build the inserted values array first, then insert it all with a single query ; 您可以先构建插入的值数组,然后通过单个查询将其全部插入; that'd be faster. 那会更快。 The query would look like... 查询看起来像...

INSERT INTO relationships (id_a, id_b) VALUES (0, 1), (0, 2), (0, 3);

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

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