如何优化SQL查询并向现有数组添加更多数组元素?

时间:2014-02-18 11:56:27

标签: php mysql sql arrays associative-array

我有一个名为$insert_users的数组如下:

Array
(
    [0] => 9def02e6337b888d6dbe5617a172c18d
    [1] => a6d22e4cc3f65778a60b359842bcec82
    [2] => e17151c98358b60910d4d9fd6ae73ac4
    [3] => 472d3d7eca74cb3518bcba787aee8540
)

现在我必须从上面的数组中为每个id发出一个SQL查询。我为此编写的代码如下:

foreach($insert_users as $key => $value ) {


$sql  = " SELECT DISTINCT ud.user_mobile_number, u.user_first_name, u.user_last_name FROM OCN.users_groups_subscribe ugs JOIN OCN.users_details ud ON ud.user_id=ugs.subscribe_user_id JOIN OCN.users u ON u.user_id=ugs.subscribe_user_id WHERE ugs.subscribe_user_id ='".$value."'";

            $this->mDb->Query( $sql);
            $students_data = $this->mDb->FetchArray();                          
            }

它返回来自$insert_users数组的单个id元素的数组:

Array
(
    [0] => Array
        (
            [user_mobile_number] => 9929933345
            [user_first_name] => Ashish
            [user_last_name] => Patil
        )

)

但我没有得到所需格式的数组。我想要以下格式的数组$students_data以及数组$insert_users中的所有值:

Array(  
     [0]=>Array
     (
        [user_full_name] => Ashish Patil //This key should be newly generated & should contain values of keys user_first_name & user_last_name concatenated to each other
        [user_mobile_number] => 9929933345
     )
)

此外,任何人都可以告诉我有没有办法只触发一次SQL查询并获得所需的数组,其中包含数组$insert_users中所有ID的详细信息?

2 个答案:

答案 0 :(得分:1)

赢得了这个帮助:

SELECT DISTINCT ud.user_mobile_number,
CONCAT(u.user_first_name,' ',u.user_last_name) AS user_full_name 
FROM OCN.users_groups_subscribe ugs
JOIN OCN.users_details ud ON ud.user_id=ugs.subscribe_user_id
JOIN OCN.users u ON u.user_id=ugs.subscribe_user_id
WHERE ugs.subscribe_user_id ='".$value."'";

答案 1 :(得分:1)

而不是做

foreach($insert_users as $key => $value ) {


    $sql  = " SELECT DISTINCT ud.user_mobile_number, u.user_first_name, u.user_last_name FROM OCN.users_groups_subscribe ugs JOIN OCN.users_details ud ON ud.user_id=ugs.subscribe_user_id JOIN OCN.users u ON u.user_id=ugs.subscribe_user_id WHERE ugs.subscribe_user_id ='".$value."'";

    $this->mDb->Query( $sql);
    $students_data = $this->mDb->FetchArray();                          
}

待办事项

$value = "'" . implode("','", $insert_users) . "'";
$sql  = " SELECT DISTINCT ud.user_mobile_number, CONCAT(u.user_first_name,' ',u.user_last_name) AS user_full_name FROM OCN.users_groups_subscribe ugs JOIN OCN.users_details ud ON ud.user_id=ugs.subscribe_user_id JOIN OCN.users u ON u.user_id=ugs.subscribe_user_id WHERE ugs.subscribe_user_id IN(" .$value . ")";

$this->mDb->Query( $sql);
$students_data = $this->mDb->FetchArray();

现在你应该在一个查询中得到你想要的所有结果