MySQL - Query combine rows with same id and keep all entry for that id but as one record

前端 未结 1 575
自闭症患者
自闭症患者 2021-02-13 15:50

I have been working on a table in a mysql database being hold locally on a wamp server I am using the phpmyadmin area with in wamp to run the querys. I am trying to get the data

1条回答
  •  悲哀的现实
    2021-02-13 16:38

    The problem is that MySQL does not have a good way of enumerating rows. The use of the constant is not guaranteed to work, alas, according to the MySQL documentation. It often does work, but it can also be problematic.

    I would suggest that you concatenate the names together into a single field. The result would look like:

    1     tree,rose
    2     tree
    3     tree,bush,rose
    

    Using the SQL:

    select plantid, group_concat(name separator ',')
    from t
    group by plantid
    

    If you really wanted the names in separate columns, two options come to mind. One is to use the results from above and then parse the result into separate strings. The other alternative is to use a self-join and aggregation to calculate a sequential number, like this:

    select p.plantid, p.name, count(*) as seqnum
    from t p left outer join
         t pprev
         on p.plantid = pprev.plantid and
            p.name >= pprev.name
    group by p.plantid, p.name
    

    And use this as the subquery.

    0 讨论(0)
提交回复
热议问题