从2个表中进行一些计算的mysql查询

时间:2015-07-06 18:59:04

标签: php mysql sql mysqli

我有两张桌子,

**Member table**

mid | parentid | name
1           1      a
2           1      x
3           1      c
4           2      d
5           3      e
6           3      f
7           4      g

**contact table** 

cid   |    mid
1           1    
2           1     
3           3      
4           2      
5           3      
6           4      
7           4   

我需要一个查询来显示成员列表,并从2个表中他们是父母的人数最多排序,所以答案将是

id | name  |rank
1      a     5
3      c     4
4      d     3
2      b     2
5      f     0
6      g     0
7      h     0

1 个答案:

答案 0 :(得分:0)

我认为使用UNION ALLGROUP BY是解决此问题的方法。这可能有用,但我还没有测试过。

SELECT
    member.mid AS id,
    member.name AS name,
    COUNT(counter.x) AS rank
FROM 
    member,
    (
        SELECT parentid AS x FROM member
        UNION ALL
        SELECT mid AS x FROM contact
    ) AS counter
WHERE
    member.mid = counter.x
GROUP BY counter.x
SORT BY counter.x DESC