SQL查询 - 从逗号分隔的一列中获取数据并按行显示

时间:2018-04-25 03:04:01

标签: mysql sql

我在获取用逗号分隔的数据时遇到问题。

这是我的问题

ab -n 10 -c 2 http://localhost:{port}

我希望得到这样的结果。例如,当用户在TD中选择14时,结果应如下所示:

Table
ID | TDNO | PREVIOUS_TD |
1  | 14   | 13,12,11    |
2  | 23   | 45,12       |
3  | 32   | 89          |
4  | 55   | NEW         |

当用户在TD中选择32时,结果应如下所示:

ID | TD  |
1  | 14  |
2  | 13  |
3  | 12  |
4  | 11  |

当用户选择23时,结果应如下所示:

ID | TD  |
1  | 32  |
2  | 89  |

如何实现这个目标?

2 个答案:

答案 0 :(得分:0)

您可以在您的SQL版本中尝试存储过程或函数。这是MySql伪代码,可能非常错误。某些SQL版本不支持返回表:

    create function returnCommaSepList (IN myId INT)
    begin
        --
        -- is mtId in the source table?
        SET @previousTD = (
            select PREVIOUS_TD 
            from TheTable
            where ID = myId
        )

        --
        -- if the result is NULL then id was not in the table, return
        if @previousTD IS NULL then return

        --
        -- create a temporary table
        create table #temp (
            id INT primary key autoincrement,
            td int
        )

        --
        -- add myId to the temp table
        insert into #temp (td) values(myId)

        --
        -- prepare to do the string handling.  Step through 
        -- @previousTD looking for commas
        SET @startPos = 0
        SET @commaPos = LOCATE(',', @previousTD, @startPos)

        --
        -- @commaPos will be NULL if the string is NULL
        if @commaPos IS NULL then return

        --
        -- @commaPos will be 0 if there are no commas in the string
        if @commaPos = 0 then 
            SET @previousTD = TRIM(@previousTD)

            --
            -- if @previousTD is empty then return
            if LENGTH(@previousTD) = 0 then return

            --
            -- @previousTD has something in it that is not a comma. 
            -- try to insert it and return
            insert into #temp (td) values(@previousTD)
            select * from #temp order bu id
            return
        endif

        --
        -- should have a @previousTD with at least 1 comma
        while @commaPos > 0
        begin
            SET @item = substring(@previousTD, @startPos, @commaPos)

            insert into #temp (td) values(TRIM(@item))

            SET @startPos = @commaPos + 1
            SET @commaPos = LOCATE(',', @previousTD, @startPos)
        end

        select * from #temp order bu id
    end

答案 1 :(得分:0)

为了创建数据库,您需要创建一个新的表,其ID为Td和tdNos,并与此关系。例如:

Table TdNos
ID | TDNO | PREVIOUS_TD |
1  | 14   | 13,12,11    |
2  | 23   | 45,12       |
3  | 32   | 89          |
4  | 55   | NEW         |

Table TdNoHistory
TdID|Priority| PREVIOUS_TD |
1   |   1    |      13     |
1   |   2    |      12     |
1   |   3    |      11     |
2   |   1    |      45     |
2   |   2    |      12     |
3   |   1    |      89     |

对于第二个表,TdId和Priority的组合是主键,它与表TdNos到TdId列的关系