2017-04-22 14 views
1

我的數據庫表「用戶」計數在其它式柱中使用相同的數據有下面詳細如何選擇和使用SQL

--------------------------------------- 
id | username | ref | email 
--------------------------------------- 
1 | name1  | 0  | [email protected] 
2 | name2  | 1  | [email protected] 
3 | name3  | 0  | [email protected] 
4 | name4  | 3  | [email protected] 
5 | name5  | 3  | [email protected] 
6 | name5  | 0  | [email protected] 
--------------------------------------- 

這意味着ID 3是4,5-引薦和id 1是引薦ID 2,因爲相同的ID顯示在列ref中。 我的問題是如何選擇ID的名稱4 & 5使用ID 3 而如何計數ID 3有多少推介? 例如ANS:NAME3 = 2 REF,NAME1 = 1 REF

+0

請顯示您的預期輸出以及您嘗試的結果?推介層次可以超過一個層次嗎? –

回答

0

使用以下在MySQL過程

CREATE PROCEDURE `get_tree`(IN `id` NUMBER) 
    BEGIN 
    DECLARE refid NUMBER; 
    DECLARE userid NUMBER; 
    SET userid = id; 
    SET refid=0; 
    SELECT `ref` into refid 
    FROM `user` WHERE `id`=userid; 
    create table IF NOT EXISTS temp_table select * from user; 
    truncate table temp_table; 
    insert into temp_table select * from user; 
    WHILE (refid is not 0) DO 
     insert into temp_table select * from user WHERE id=userid; 
     SET userid = refid; 
     SET refid=0; 
     SELECT ref into refid 
     FROM user WHERE id=userid; 
    END WHILE; 
    select * from temp_table; 
    END 
1

可以選擇通過下面的查詢其裁判是ID 3的用戶:

SELECT * FROM data WHERE ref = 3 

輸出:

id username ref email 
4 name4  3 [email protected] 
5 name5  3 [email protected] 

而且您可以統計ref編號爲3的用戶數:

SELECT count(id) FROM data WHERE ref = 3 

輸出:

count(id) 
2 
0

嘗試

select username, (select count(ref) from user u2 where u2.ref = u.id group by ref) as refcount from user u

或者

SELECT u.username, count(u2.id) from user u left join user u2 on u2.ref = u.id group by u.id, u.username having count(u2.id) > 0

0
select (select u2.username from user u2 where u2.id = u1.ref), count(*) as refs from user u1 where u1.ref > 0 group by u1.ref 

這是我的測試代碼:

drop table if exists `user`; 

create table if not exists `user`(
    id int primary key auto_increment, 
    name nvarchar(250), 
    ref int 
); 

insert into `user`(id, name, ref) values (1, 'user1', 0); 
insert into `user`(id, name, ref) values (2, 'user2', 1); 
insert into `user`(id, name, ref) values (3, 'user3', 1); 
insert into `user`(id, name, ref) values (4, 'user4', 2); 
insert into `user`(id, name, ref) values (5, 'user5', 3); 

select (select u2.name from `user` u2 where u2.id = u1.ref), count(*) as refs from `user` u1 where u1.ref > 0 group by u1.ref 

和出放爲:

|名稱|裁判|

| use1 | 2 |

| use2 | 1 |

| use3 | 1 |