根据ID从两个表中获取记录数组

时间:2019-07-26 12:52:42

标签: mysql

我有两个具有相同ID的表,并且我尝试使用group concat离开与另一个数组表的连接,但是它两次返回值,因为我希望在插入表单时使用group concat数据

我尝试了很多查询,但没有期望的输出,这些是我为简单起见而实际编写的代码,我上传了一个示例表,希望输出图片

DROP TABLE IF EXISTS Table1;

CREATE TABLE Table1
(id SERIAL PRIMARY KEY);

INSERT INTO Table1 VALUES(15),(16),(17);

DROP TABLE IF EXISTS Table2;

CREATE TABLE Table2
(id INT NOT NULL
,data CHAR(2) NOT NULL
,PRIMARY KEY(id,data)
);

INSERT INTO Table2 VALUES
(15,'A1'),
(15,'B1'),
(15,'C1'),
(16,'H');

Expected output:
id data
15 A1,B1,C1
16 H
17 NULL

我的应用程序的实际代码

select 
v.user,
v.type,
v.registrationNumber,
group_concat(c.type) contacts_type,
group_concat(c.mobilenumber) mobilenumbers,
group_concat(p.state) states,
group_concat(p.validUpto) validuptos
from m_vehicle v
left join m_av_contacts c 
        on   c.vehicleno = v.registrationNumber
left join m_av_permits p
        on c.vehicleno = p.vehicleno
        where v.user='santhosh' group by v.registrationNumber

2 个答案:

答案 0 :(得分:0)

SELECT t1.id
     , GROUP_CONCAT(t2.data ORDER BY t2.data) x
  FROM Table1 t1 
  LEFT 
  JOIN Table2 t2 
    ON t2.id = t1.id 
 GROUP 
    BY t1.id;
+----+----------+
| id | x        | 
+----+----------+
| 15 | A1,B1,C1 |
| 16 | H        |
| 17 | NULL     |
+----+----------+

答案 1 :(得分:0)

TypedParameter