问题
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