MySQL complex self join

一个人想着一个人 提交于 2019-12-11 06:03:04

问题


I having a table like this:

id | name
--------
1  | test
2  | test1
3  | test
4  | test1
5  | test2

I am trying to write a query that will give a result like this

 test   |  test1 | test2
----------------------------
 1      |   2    |   5
 3      |   4    |

And it is very clear there will be only three name, I am trying to write the query, But I couldn't. Can someone help me


回答1:


Well, just to appease the doubters. Note, I'm not seriously advocating this as a solution, because it's just not very scalable - and making it scalable (via prepared statements and a sproc is, frankly, tedious)...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL PRIMARY KEY
,name VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(1  ,'test'),
(2  ,'test1'),
(3  ,'test'),
(4  ,'test1'),
(5  ,'test2');


SELECT MAX(CASE WHEN name = 'test' THEN id END) 'test' 
     , MAX(CASE WHEN name = 'test1' THEN id END) 'test1' 
     , MAX(CASE WHEN name = 'test2' THEN id END) 'test2' 
  FROM 
     ( SELECT x.*
            , COUNT(*) rank 
         FROM my_table x 
         JOIN my_table y 
           ON y.name = x.name 
          AND y.id <= x.id 
        GROUP 
           BY id
     ) z GROUP BY rank;

+------+-------+-------+
| test | test1 | test2 |
+------+-------+-------+
|    1 |     2 |     5 |
|    3 |     4 |  NULL |
+------+-------+-------+


来源:https://stackoverflow.com/questions/20269637/mysql-complex-self-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!