How to merge data from 2 tables with MySQL

99封情书 提交于 2019-12-12 02:48:45

问题


I have 2 tables set up something like below, what MySQL querys do I need to use to return assoc arrays of each entry along with it's associated fields? I've tried various JOINs but they all return a result for every item in the second table. Ultimately I want a parent array with one child array for each item in the first table. Each child array would contain the name from table A along with all the fields that belong to it from table B where B.entryID = A.ID.

A
ID    |Name    |Created
1     Jeff     2013-20-12
2     Bob      2011-23-14

B
ID    |Value   |FieldID    |entryID
1     U.S      1            1
2     91725    2            1
3     China    1            2

DESIRED STRUCTURE

Array
(
    [0] => Array
        (
            [0] => Jeff
            [1] => U.S
            [2] => 91420
        )

    [1] => Array
        (
            [0] => Bob
            [1] => China
            [2] => 
        )

)

回答1:


SELECT A.Name, B.Value from A LEFT JOIN B on A.ID=B.entryID



回答2:


Okay, so there are a few ways to do this...

Method 1

If you take out the array bit and were to handle your data more appropriately the right way to do this would be:

SELECT `A`.`ID`, `A`.`Name`, `B`.`Value`
FROM A
INNER JOIN
  `B` ON `A`.`ID` = `B`.`entryID`
ORDER BY `A`.`ID`, `B`.`Value`

This will return results like:

array(
  0 => array(ID=>1, Name=>'Jeff', Value=>'U.S'),
  1 => array(ID=>1, Name=>'Jeff', Value=>'91725'),
  2 => array(ID=>2, Name=>'Bob',  Value=>'China')
)

Which you would iterate through like so (you could modify this to create the array structure you're after as opposed to echoing to a string...):

$mysqli = new mysqli(...);//Make your db connection
$query  = $mysqli->query("
    SELECT `A`.`ID`, `A`.`Name`, `B`.`Value`
    FROM A
    INNER JOIN
      `B` ON `A`.`ID` = `B`.`entryID`
    ORDER BY `A`.`ID`, `B`.`Value`
    ");
$newArr = array();
$lastID = '';
if($query->num_rows){
    while($row = $query->fetch_assoc()){
        if($lastID == $row['ID']){
            end($newArr);
            $key = key($newArr);
            $newArr[$key][] = $row['Value'];
        }
        else{
            $newArr[] = array($row['Name'], $row['Value']);
        }
        $lastID = $row['ID'];
    }
}
var_export($newArr);

/**
Output:

array (
  0 => 
  array (
    0 => 'Jeff',
    1 => 'U.S.',
    2 => '91275',
  ),
  1 => 
  array (
    0 => 'Bob',
    1 => 'China',
  ),
)

*/

Method 2

If you really want/need to output as an array from the SQL query then I'd suggest something like the following:

SELECT
    A.ID, A.Name,
    CONCAT(
      '[',
      GROUP_CONCAT('"', B.Value, '"'),
      ']'
    ) as Values
FROM A
INNER JOIN B ON B.entryID = A.ID
GROUP BY A.ID

Which would output Values as json:

array(
    0=>arryay(ID=>1, Name=> 'Jeff', Values='["U.S.", "91725"]'),
    1=>arryay(ID=>1, Name=> 'Bob',  Values='["China"]')
)

and you would need to run json_decode on the Values each time you accessed the record in php. Something like:

$mysqli = new mysqli(...);//Make your db connection
$query  = $mysqli->query("
    SELECT
        A.ID, A.Name,
        CONCAT(
          '[',
          GROUP_CONCAT('"', B.Value, '"'),
          ']'
        ) as Values
    FROM A
    INNER JOIN B ON B.entryID = A.ID
    GROUP BY A.ID
    ");

$newArr = array();
if($query->num_rows){
    while($row = $query->fetch_assoc()){
        $newArr[] = array($row['Name']);
        end($newArr);
        $key = key($newArr);
        $fieldData = json_decode($row['Values']);
        foreach($fieldData as $value){
            $newArr[$key][] = $value;
        }
    }
}
var_export($newArr);


/**
Output:

array (
  0 => 
  array (
    0 => 'Jeff',
    1 => 'U.S.',
    2 => '91275',
  ),
  1 => 
  array (
    0 => 'Bob',
    1 => 'China',
  ),
)

*/

NOTE: I suggest that you don't do it this way... As it could lead to all sorts of bugs if your data isn't stored in a way that can allow for this (e.g. if you haven't encoded/escaped "). You might also run into problems if there is a large amount of data being pulled from B...



来源:https://stackoverflow.com/questions/19021631/how-to-merge-data-from-2-tables-with-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!