亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試合并 SQL 查詢的兩個結果

嘗試合并 SQL 查詢的兩個結果

PHP
慕絲7291255 2022-10-09 16:20:39
我正在嘗試使用 PHP 在 MYSQL 中合并兩個查詢的兩個結果,但我很困惑如何去做!我正在使用 PDO。我正在為一種愛好編程,并正在嘗試制作一個待辦事項列表應用程序,就像 Trello 板一樣。但是,我只是不知道如何合并來自數據庫中不同表的兩個結果。思路如下:我有一個名為“task_lists”的表格,內容如下:'list_id => 1, list_name = 'listOne''list_id => 2, list_name = 'listTwo'還有一個名為“任務”的表:task_id => 1, list_id => 1, task_name => 'taskOfListOne', duration => 5, is_done => 1task_id => 2, list_id => 1, task_name => 'anotherTaskOfListOne', duration => 5, is_done => 1task_id => 3, list_id => 2, task_name => 'taskOfListTwo', duration => 10, is_done => 0我正在嘗試創建一個在兩個結果之間合并的數組,如下所示:(我知道這是數組應該是什么樣子的粗略圖片)$result = [array][list_id] = 1, [list_name] = 'listOne' =>                      [array][list_id] = 1, ['task_name] = taskOfListOne,[duration] = 5, ['is_done'] => 1                     [array][list_id] = 1, ['task_name] = anotherTaskOfListOne,[duration] = 5, ['is_done'] => 1[list_id] = 2, [list_name] = 'listTwo' =>                     [array][list_id] = 2, ['task_name] = taskOfListTwo,[duration] = 5, ['is_done'] => 1這甚至可能嗎?我已經嘗試過 Union sql 查詢和嵌套 foreach 語句之類的方法,但它們都不適合我。我在這里錯過了什么嗎?PS:對不起我的英語不好。
查看完整描述

1 回答

?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

你試過左連接嗎?


SELECT TL.`list_id`, TL.`list_name`, T.`task_name`, T.`duration`  

FROM task_lists AS TL

LEFT JOIN tasks as T ON TL.`list_id` = T.`list_id`

然后在 PHP 中,您以所需的格式構建數組。


稍后編輯: 根據您的要求解析 SQL 數據的簡單 PHP 示例(刪除重復信息):


<?php

// $mysql_rows -> here is your query result, fetched as associative array

$filtered_array = array();

foreach ($mysql_rows as $row){


    // Initiate record if is not already initiated

    if (!isset($filtered_array[ $row['list_id'] ])){

        $filtered_array[ $row['list_id'] ] = array(

            'list_id'   => $row['list_id'],

            'list_name' => $row['list_name'],

            'tasks'     => array()

        );

    }


    // Add tasks

    $filtered_array[ $row['list_id'] ]['tasks'][] = array(

        'task_name'  => $row['task_name'],

        'duration'   => $row['duration'],

        'is_done '   => $row['is_done ']

    );

}


// Optional: if you want to remove list_id from $filtered_array key names, uncomment the next line

// $filtered_array = array_values($filtered_array);

?>


查看完整回答
反對 回復 2022-10-09
  • 1 回答
  • 0 關注
  • 153 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號