duangou1551 2013-11-28 14:52
浏览 147
已采纳

MySQL数据库中每个字段的多个值

  • First of all: I know that its really bad style to work with multiple entries in one field, but I did not create the database myself and now I have to work with it. It has around 20000 entries and I really dont want to change it at the moment.
  • The table A I'm talking about has a column with some ID's, e.G.: ,282,3358,123,
  • Those ID's are matching with the primary keys of some other table B. B has another column name.
  • I want to get those names into my table A replacing those ID's
  • Example:

Table B

| ID |      name         |     
+----+-------------------+
|282 |      name_1       |
+----+-------------------+
|3358|      name_2       |
+----+-------------------+
|123 |      name_3       |

Initial Situation TABLE A

 ... |         ID             | ...    
-----+------------------------+-----
 ... |    ,282,3358,123,      | ... 

Desired Result for TABLE A

 ... |         ID             | ...    
-----+------------------------+-----
 ... | ,name_1,name_2,name_3, | ...  
  • 写回答

2条回答 默认 最新

  • douye2488 2013-12-05 14:34
    关注

    I found a way how do deal with my problem. However it's really not recommendable to use multiple entries per field. But if your in a situation like me, where you have to work with such an unrelational schemed database without being allowed to change the scheme, here we are:

    SELECT [...] ,
    (SELECT GROUP_CONCAT( table_B.name SEPARATOR ',' ) FROM table_B 
    WHERE FIND_IN_SET ( B.ID , SUBSTRING ( table_A.ID , 2 , length( table_A.ID ) -2 ) ) >0 ) ,
    [...]
    FROM table_A
    

    Some Explanations:

    • the SUBSTRING is needed in order to remove the "," in the begining of the multiple field entry. E.g.: SUBSTRING ( ",282,3358,123," , 2 , length( ",282,3358,123," ) -2 ) results in "282,3358,123"
    • the FIND_IN_SET method searches a value into a comma separated string list and returns the index of the value. If no value can be found, it returns 0. Thats why I compare the whole string against 0.
    • the GROUP_CONCAT method concatenates the matching names. As a result it delivers a comma separated string list ==> name_1,name_2,name_3

    Some Annotations:

    • Using this query is very inefficient. That query has to deal with at least #ROWS_IN_TABLE_A * #ROWS_IN_TABLE_B table rows
    • Regarding perfomance issues, one should precompute the table and store it into a database (thats what I did).
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?