将tblB中的用户ID从tblA加入用户并获取用户名

时间:2014-02-19 14:35:19

标签: mysql sql

如何将userid加入用户并获取用户名? 我非常感谢任何帮助。谢谢你。

http://sqlfiddle.com/#!2/ac600/1

   CREATE TABLE if not exists tblA
(
id int(11) NOT NULL auto_increment ,
user varchar(255),
 category int(255),
 PRIMARY KEY (id)
);

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


INSERT INTO tblA (user, category ) VALUES
('1', '1'),
('1', '2'),
('1', '3'),
('1', '1'),
('2', '1'),
('2', '1'),
('2', '1'),
('2', '1'),
('3', '1'),
('2', '1'),
('4', '1'),
('4', '1'),
('2', '1');


INSERT INTO tblB (userid, username ) VALUES
('1', 'A'),
('2', 'B'),
('3', 'C'),
('4', 'D'),
('5', 'E');

查询:

SELECT
  groups.*,
  @rank:=@rank+1 AS rank
FROM
  (select 
    user,
    category,
    count(*) as num
  from 
    tblA
  where 
    category=1 
  group by 
    user, 
    category
  order by 
    num desc,
    user) AS groups
  CROSS JOIN (SELECT @rank:=0) AS init

表格如下:

username    category    num Ascending   rank    
B   1   6   2
A   1   2   1
D   1   2   4
C   1   1   3

3 个答案:

答案 0 :(得分:1)

使用JOIN,例如:

SELECT
  tblB.username,
  groups.*,
  @rank:=@rank+1 AS rank
FROM
  (select 
    user,
    category,
    count(*) as num
  from 
    tblA
  where 
    category=1 
  group by 
    user, 
    category
  order by 
    num desc,
    user) AS groups
  -- left join: in case if data integrity fails:
  left join
    tblB ON groups.user=tblB.userid
  CROSS JOIN (SELECT @rank:=0) AS init

- 检查修改后的demo

答案 1 :(得分:0)

你只需要做左连接

SELECT
   groups.*,
 @rank:=@rank+1 AS rank
 FROM
 (select 
user,
category,
count(*) as num,
tblB.username
from 
tblA
 left join tblB on tblA.id = tblB.userid
where 
category=1 
group by 
user, 
category
order by 
num desc,
user) AS groups
CROSS JOIN (SELECT @rank:=0) AS init

请参阅Demo

答案 2 :(得分:0)

您不需要子查询来执行您想要的操作。您只需加入名称:

  select username, category,
          count(*) as num,
          @rank:=@rank+1 AS rank
  from tblA join
       tblB
       on tblA.user = tblB.userId CROSS JOIN
       (SELECT @rank:=0) AS cont
  where category = 1 
  group by username, category
  order by num desc, username;

TblB格式奇怪。通常,自动递增ID将是表的“用户ID”。

另外,因为您只选择了一个类别,所以严格来说不必将category放在group by语句中。

编辑:

您无法使用此rank方法创建视图,因为它使用变量。在MySQL中以视图兼容的方式生成聚合数据的排名并不容易。