有可能从另一个表中的单元格中获取make数组导致mysql

时间:2016-08-04 10:57:52

标签: mysql

我有两个表,我从表中得到了结果 这是表

        Table1      
+-------------------+   
|   APH |   ID      |
+-------------------+   
|   A   |   ID01    |
|   B   |   ID02    |
|   C   |   ID03    |
|   D   |   ID04    |
+-------------------+   

        Table2  
+-------------------+   
|   ID      | Value |
+-------------------+
|   ID01    |   10  |
|   ID01    |   15  |
|   ID01    |   20  |
|   ID01    |   25  |
|   ID02    |   6   |
|   ID02    |   18  |
|   ID02    |   30  |
|   ID02    |   42  |
|   ID02    |   54  |
|   ID03    |   7   |
|   ID03    |   15  |
|   ID03    |   23  |
|   ID03    |   31  |
+-------------------+

例如: -

我必须从ID = ID01

的表中获取所有值

所以可以得到这样的结果。?

        Result      
+-----------------------------------+
|   APH |   ID      |   Value       |
+-----------------------------------+
|   A   |   ID01    |[10,15,20,25]  |
+-----------------------------------+


并为所有结果

        Result      
+-----------------------------------+
|   APH |   ID0     |   Value       |
+-----------------------------------+
|   A   |   ID01    |[10,15,20,25]  |
|   B   |   ID02    |[6,18,30,42,54]|
|   C   |   ID03    |[7,15,23,31]   |
|   D   |   ID04    |               |
+-----------------------------------+

2 个答案:

答案 0 :(得分:1)

您需要使用GROUP_CONCAT

  

MySQL GROUP_CONCAT()函数返回一个连接的字符串   来自某个组的non-NULL值。

     

如果没有NULL值,则返回non-NULL

SELECT 
 APH,
 ID,
 CONCAT('[',GROUP_CONCAT(T2.`value`),']') AS output
FROM Table1 AS T1 
INNER JOIN Table2 AS T2
ON T1.ID = T2.ID
WHERE T1.ID ='ID01'

修改

如果您只想要以逗号分隔的列表,请离开CONCAT部分。

SELECT 
 APH,
 ID,
 GROUP_CONCAT(T2.`value`) AS output
FROM Table1 AS T1 
INNER JOIN Table2 AS T2
ON T1.ID = T2.ID
WHERE T1.ID ='ID01'

<强> EDIT2:

SELECT 
 APH,
 ID,
 GROUP_CONCAT(T2.`value`) AS output
FROM Table1 AS T1 
INNER JOIN Table2 AS T2
ON T1.ID = T2.ID
GROUP BY T1.ID;

答案 1 :(得分:0)

我相信这有助于你得到你想要的东西

Select 
    t1.APH,t1.ID Group_Concat(t2.Value) Over (Partition By t1.ID) As Value
From 
    Table1 t1 
Inner Join 
    Table2 t2 on tr.ID=t2.ID
Where
    t1.ID = 'ID01'