从正确的表格结果中获取多维数组

时间:2018-08-17 07:45:14

标签: mysql sql mariadb

我有两个桌子。第一个是客户信息,第二个是电话号码。 因此,在第一个表中,我将拥有:

ID   Name
1    John
2    jill

在第二张表中,我将拥有:

ID    phone     ext   notes                  customerID
1     687-5309  20    Primary                1   
2     687-5310  55    John's cell phone      1
3     687-5311  18    Note! Emergency Only!  1
4     235-1189                               2 
5     235-2324  24     title:owner           2 

当我查询它时,我希望它从正确的表中给出多维结果。因此结果将是:

[ID]=>1
[Name]=>John
[phoneList]=>[ 
     [
          [ID]=>1 , [phone]=>687-5309 , [ext]=>20 , [notes]=>Primary ],
          [ID]=>2 , [phone]=>687-5310] , [ext]=>55 , [notes]=>John's cell phone ], 
          [ID]=>3 , [phone]=>687-5311] , [ext]=>18 , [notes]=>Note! Emergency Only! ],
     ]

]

到目前为止,这是我所能得到的:

SELECT * 
FROM customer_info
LEFT JOIN (
 SELECT * 
 FROM phone_numbers
) WHERE ID=1

我什至不确定这是否可行。但是感觉应该是这样。

1 个答案:

答案 0 :(得分:1)

如果没有对customer_info进行分组,那么这只是一个简单的LEFT JOIN。

SELECT cust.*, phone.ID AS phone_id, phone.phone, phone.ext, phone.notes
FROM customer_info AS cust
LEFT JOIN phone_numbers AS phone ON phone.customerID = cust.ID
WHERE cust.ID = 1;

但是,如果您想要每个customer_info ID一条记录吗?
然后,您也可以GROUP BY的customer_info,然后使用GROUP_CONCAT来获得1个带有电话ID和电话号码的字符串。

SELECT cust.ID, cust.Name, 
 group_concat(concat(phone.ID,':',concat_ws(',', phone.phone, ifnull(phone.ext,''), phone.notes)) separator ';') AS phoneList
FROM customer_info AS cust
LEFT JOIN phone_numbers AS phone ON phone.customerID = cust.ID
WHERE cust.ID = 1
GROUP BY cust.ID, cust.Name;

如果您的版本中提供了JSON_OBJECT(MariaDBMySql)函数,则可以使用它。

SELECT cust.ID, cust.Name, 
group_concat(JSON_OBJECT('id', phone.ID, 'phone', phone.phone, 'ext', phone.ext, 'notes', phone.notes)) AS phoneList
FROM customer_info AS cust
LEFT JOIN phone_numbers AS phone ON phone.customerID = cust.ID
WHERE cust.ID = 1
GROUP BY cust.ID, cust.Name;

db <>小提琴here

上进行测试