结合这三个SELECT语句是否可行且谨慎?

时间:2015-05-12 16:15:43

标签: mysql

我有以下MySQL表:

LEVEL(lid)    USERS(uid,name,l_id)   USERS_G(u_id,r_id,flag)   REQUESTS(rid,status)
---------------------------------------------------------------------------------
  1              1  John   1         1  96   1                  96    0
  2              2  Peter  1         1  97   1                  97    0
  3              3  Helen  2         2  97   0                  98    0 
                                     3  97   0                  99    1 
                                     2  98   1
                                     1  98   0
                                     3  98   0

对用户1:N,USERS对USERS_G 1:N,要求USERS_G 1:N。

我想从REQUESTS中选择具有特定状态的记录,同时这些请求记录的用户持有者具有一定的级别。如果USERS_G中的相应标志等于1,则认为用户是请求的持有者。这很容易,并按如下方式实现:

SELECT lid,rid,name FROM REQUESTS JOIN USERS_G 
        ON REQUESTS.rid = USERS_G.r_id AND flag=1 AND status='0'
        JOIN USERS 
        ON USERS_G.u_id=USERS.uid
        JOIN LEVEL 
        ON LEVEL.lid=USERS.l_id AND LEVEL.lid='1';   

以上查询的结果是:

1    96    John
1    97    John
1    98    Peter

到目前为止,这么好。此外,我想找到与之前的任何请求相关联的记录数。换句话说:

SELECT COUNT(*) FROM REQUESTS JOIN USERS_G 
        ON REQUESTS.rid = USERS_G.r_id
        WHERE REQUESTS.status='0' GROUP BY REQUESTS.rid;

1
3
3

我还没完成!我还想在字符串中使用相应的名称:

SELECT GROUP_CONCAT(USERS.name SEPARATOR '\n') FROM USERS,USERS_G,REQUESTS
WHERE uid=u_id AND r_id=rid AND status=0 GROUP BY rid;

为了使事情更加全面,我想要以下结果 一个查询?

 Level       Rid   Holder Name       Count       Concat
---------------------------------------------------------------
 1            96      John              1          John
 1            97      John              3          John  Peter Helen
 1            98      Peter             3          John  Peter Helen 

实现这一目标是否可行?很明显,这个查询必须尽快执行。

提前谢谢

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是在所有3个查询中选择rid并将查询联合在一起。例如。像这样的东西:

SELECT r.*, counts.count, names.concat

FROM (
    SELECT lid,rid,name FROM REQUESTS JOIN USERS_G 
        ON REQUESTS.rid = USERS_G.r_id AND flag=1 AND status='0'
        JOIN USERS 
        ON USERS_G.u_id=USERS.uid
        JOIN LEVEL 
        ON LEVEL.lid=USERS.l_id AND LEVEL.lid='1' 
    ) AS r
JOIN (
    SELECT rid, COUNT(*) as count FROM REQUESTS JOIN USERS_G 
        ON REQUESTS.rid = USERS_G.r_id
        WHERE REQUESTS.status='0' GROUP BY REQUESTS.rid
    ) AS counts ON counts.rid = r.rid
JOIN (
    SELECT rid, GROUP_CONCAT(USERS.name SEPARATOR '\n') AS concat FROM USERS,USERS_G,REQUESTS
    WHERE uid=u_id AND r_id=rid AND status=0 GROUP BY rid;
    ) AS names ON names.rid = r.rid