我目前have a question about this,但我不認爲這是可能接受它的擴展名和版本的整個時間,因爲它應有的重視。有了這個,我會努力盡可能簡潔,放手!試圖讓行位置正確
我想獲得一個特定的表的行位置,在此SQLFiddle
我現在有上2個查詢:一個是列出了列級排序它們(這是一個COUNT所有行()其他行);和其他獲得特定行信息的其他人。
在這個屏幕截圖的SQLFiddle的,我目前的結果,並且在黃色(毗鄰位置列)我有希望的結果。你可以看到,「位置」所指的可能是列ID,不列秩,因爲它應該是:
我怎樣才能達到預期的效果?
萬一小提琴不加載,這裏的所有DLL:
模式:
CREATE TABLE IF NOT EXISTS `site_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
INSERT INTO `site_users` (`id`, `username`) VALUES
(1, 'Mateus'),
(2, 'Marco'),
(3, 'John'),
(4, 'Luke'),
(5, 'Wall');
CREATE TABLE IF NOT EXISTS `site_articles_comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`data` int(11) NOT NULL,
`comment` text NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
INSERT INTO `site_articles_comments` (`id`, `user_id`, `data`, `comment`) VALUES
(1, 1, 1492101324, 'Too good to be true'),
(2, 1, 1492101392, 'It\'s so, not very.'),
(3, 1, 1492106262, 'I loved it!'),
(4, 3, 1492107619, 'Seems fishy'),
(5, 1, 1492108002, 'Don\'t blame it on her'),
(6, 2, 1492108433, 'As I highly doubt it'),
(7, 2, 1492200402, 'This is just a test'),
(8, 2, 1492267629, 'Another test'),
(9, 2, 1492267684, 'No sht'),
(10, 4, 1492267766, 'WTF?'),
(11, 2, 1492267796, 'Pics, pleaseee!');
測試查詢:
/* This simply order users on rank (rank being number of comments) */
/* This query tries to get the row position of user based on rank */
SELECT x.id,
x.username,
x.rank,
x.position
FROM (SELECT u.id,
u.username,
@rownum := @rownum + 1 AS position,
(SELECT COALESCE(COUNT(DISTINCT(c.id)),0) AS rank
FROM site_articles_comments c
WHERE u.id = c.user_id ORDER BY rank DESC) AS rank
FROM site_users u
JOIN (SELECT @rownum := 0) r
ORDER BY rank DESC) x;
/* Based on the list above, user (Marco) should have a position number of 1 */
SELECT x.id,
x.username,
x.rank,
x.position
FROM (SELECT u.id,
u.username,
@rownum := @rownum + 1 AS position,
(SELECT COALESCE(COUNT(DISTINCT(c.id)),0) AS rank
FROM site_articles_comments c
WHERE u.id = c.user_id ORDER BY rank DESC) AS rank
FROM site_users u
JOIN (SELECT @rownum := 0) r
ORDER BY rank DESC) x
WHERE x.id = 2
可能重複[獲取不同行的COUNT()的行位置](http://stackoverflow.com/questions/43437680/get-row-position-of-count-of-distinct-rows) – Shadow
不要無論原因是什麼,都要問同樣的問題兩次。 – Shadow
好的,然後我刪除了原來的問題。 –