2014-02-10 89 views
1

如何根據積分排列以下用戶的排名。我真的很感激任何幫助。 在此先感謝。根據積分排名的用戶

http://sqlfiddle.com/#!2/374db/11

CREATE TABLE if not exists tblA 
(
id int(11) NOT NULL auto_increment , 
sender varchar(255), 
receiver varchar(255), 
msg varchar(255), 
date timestamp, 
    points varchar(255), 
    refno varchar(255), 
PRIMARY KEY (id) 
); 

CREATE TABLE if not exists tblB 
(
id int(11) NOT NULL auto_increment , 
sno varchar(255), 
name varchar(255), 
PRIMARY KEY (id) 
); 

CREATE TABLE if not exists tblC 
(
id int(11) NOT NULL auto_increment , 
data varchar(255), 
    refno varchar(255), 
    extrarefno varchar(255), 
PRIMARY KEY (id) 
); 


INSERT INTO tblA (sender, receiver,msg,date,points,refno) VALUES 
('1', '2', 'buzz ...','2011-08-21 14:11:09','10','001'), 
('1', '2', 'test ...','2011-08-21 14:12:19','20','002'), 
('4', '2', 'test ...','2011-08-21 14:13:19','30','003'), 
('1', '3', 'buzz ...','2011-08-21 14:11:09','10','004'), 
('1', '3', 'test ...','2011-08-21 14:12:19','20','005'), 
('1', '4', 'buzz ...','2011-08-21 14:11:09','10','006'), 
('1', '4', 'test ...','2011-08-21 14:12:19','20','007'), 
('3', '4', 'test ...','2011-08-21 14:13:19','20','008'), 
('2', '4', 'test ...','2011-08-21 14:13:19','20','009'); 



INSERT INTO tblB (sno, name) VALUES 
('1', 'Aa'), 
('2', 'Bb'), 
('3', 'Cc'), 
('4', 'Dd'), 
('5', 'Ee'), 
('6', 'Ff'), 
('7', 'Gg'), 
('8', 'Hh'); 


INSERT INTO tblC (data,refno,extrarefno) VALUES 
('data1', '001', '101'), 
('data2', '002', '102'), 
('data3', '003', '103'), 
('data4', '004', '101'), 
('data5', '005', '102'), 
('data6', '006', '103'), 
('data7', '007', '101'), 
('data8', '008', '101'), 
('data9', '009', '101'); 

SQL

SELECT * 
FROM (SELECT tblA.receiver, MAX(tblA.id) AS id 
     FROM tblA 
     GROUP BY tblA.receiver 
    ) subset JOIN 
    tblA 
    ON subset.receiver = tblA.receiver AND subset.id = tblA.id JOIN 
    tblB 
    on tblA.receiver = tblB.sno join 
    tblC 
    ON tblA.refno=tblC.refno ; 
+1

你能更好地解釋你的模式和數據嗎?您的超級通用表名稱並不能讓我們深入瞭解您的查詢的真實含義,以及它爲什麼會出錯。你現在從查詢中得到什麼結果與你在找什麼結果? –

+0

爲什麼列是用戶? – malta

+0

是基於每個tblA條目或發件人的積分總和嗎?看一看密集的等級()(按點數排序)。這可能是你以後的事情。 –

回答

0

您可以訂購使用ORDER BY查詢的結果。所以,你可以按如下方式排列tblA中的行:

SELECT * 
FROM tblA 
ORDER BY points 

但是,我注意到你正在使用varchar作爲points列。如果這是一個數值,你可能需要int或float。

+0

可以使用'ORDER BY CAST(點作爲UNSIGNED)DESC',但我期待做一個這樣的視圖,所以我想要這樣的查詢'CREATE VIEW v AS SELECT name, (select count(*) from用戶u2 其中u2.points> u.points或 u2.points = u.points和u2.sno <= u.sno )作爲等級 FROM'users' u;'儘管查詢接下來會工作我無法轉換它到視圖中:'CREATE VIEW v AS SELECT name,points,sno,@ rownum:= @rownum + 1 AS rank FROM users,(Select @rownum:= 0) GROUP BY名稱,sno ORDER BY CAST指向AS UNSIGNED)DESC;' – jason