简体   繁体   English

如何将具有相似列的两个表联接到一个表中

[英]How to join two tables with one similar column into one table

I have 3 tables, A and B and C. 我有3张桌子,A,B和C。

sample data for Table A 表A的样本数据

nid   tid
101    3
101    4
101    7
103    3
103    5
104    2
104    4
104    7

sample data for Table B 表B的样本数据

tid   name
2     ram
3     shyam
4     krishna
5     shiv
7     narad

What I want is, in a Third Table C 我想要的是在第三张表C中

id   nid   labels
1    101   shyam, krishna, narad
2    103   shyam, shiv
3    104   ram, krishna, narad

I know how to do this with PHP, but is there any way to do this mysql alone? 我知道如何用PHP做到这一点,但是有什么办法可以单独使用mysql吗?

Both tables (A and B) have thousands of records and don't have any unique column at the moment. 两个表(A和B)都有成千上万的记录,目前没有任何唯一的列。

I tried GROUP_CONCAT but I could not construct desired output. 我尝试了GROUP_CONCAT,但无法构造所需的输出。

Edit 1 - I forgot to mention that Table C already has id and nid column inserted, while labels column is empty. 编辑1-我忘记提及表C已经插入了id和nid列,而label列为空。 So I need help in constructing some query which can update all records of Table C with labels mentioned as above. 因此,在构建一些查询时需要帮助,该查询可以使用上述标签更新表C的所有记录。

Thanks. 谢谢。 Regards, 问候,

This will insert the records on TableC . 这将在TableC上插入记录。 Since ID is an autogenerated column, you can omit this in the INSERT clause. 由于ID是自动生成的列,因此可以在INSERT子句中忽略它。

INSERT INTO TableC(Nid, Labels)
SELECT  a.nid, GROUP_CONCAT(b.Name) Labels
FROM    TableA a
        INNER JOIN TableB b
            ON a.tid = b.tid
GROUP   BY a.nid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM