获取特定用户的状态计数

时间:2018-02-07 12:06:05

标签: php mysql sql laravel-5

第一张表:详细信息

-------------------------------------
S.no  |   j_id  |age | status |
-------------------------------------
 1    |     1   |32  |  1     |
-------------------------------------
-------------------------------------
 1    |     1   |32  |  1     |
-------------------------------------
-------------------------------------
 1    |     2   |32  |  1     |
-------------------------------------
-------------------------------------
 1    |      2   |32  |  2     |
-------------------------------------
-------------------------------------
 1    |     1   |32  |  3     |
-------------------------------------
-------------------------------------
 1    |     3   |32  |  1     |
-------------------------------------

Here 1=Active 2=Inactive 3=pending

我有第二张桌子:我的

---------------------------------
S.no  | Name |  lname     |age |  
---------------------------------
 1    | ankit|     nath   |32  |  
--------------------------------
---------------------------------
 2    | neha |     nath   |32  |  
--------------------------------
---------------------------------
 3    | neraj|     nath   |32  |  
--------------------------------

这里我有两个表我想要特定名称的状态计数

就像我有Name ankit我想要ankit活动计数是:2 ankit非活动计数是:0和挂起计数是:1结果应该是那样..对于所有的矿名表我怎么能在mysql和in中取得这个laravel DB:选择通过帮助我预先关联这个thanx

2 个答案:

答案 0 :(得分:0)

SELECT  Name ,lname,age,Count(status) as StatusCount  FROM YourTable GROUP BY status,Name

输出就像这样:

---------------------------------
S.no  | Name |  lname     |age |  
---------------------------------
 1    | ankit|     nath   |32  |  
--------------------------------
---------------------------------
 2    | neha |     nath   |32  |  
--------------------------------
---------------------------------
 3    | neraj|     nath   |32  |  

--------------------------------

SELECT  Name ,lname,age,Count(status) as StatusCount   FROM YourTable WHERE Name='ankit' GROUP BY status,Name;

输出:

---------------------------------
S.no  | Name |  lname     |age |  
---------------------------------
 1    | ankit|     nath   |32  |  

答案 1 :(得分:0)

您必须使用用户的s_no获取用户数据,我认为这是用户的ID。然后将此数据与详细信息表的数据连接或映射,将输出分组到id和名称,并计算不同的状态值。作为示例,下面的查询可以为s_no=1的用户提供您想要的内容。

SELECT A.s_no, A.name, a.lname, SUM(IF(B.status=1,1,0)) Active, 
SUM(IF(B.status=2,1,0)) Inactive, SUM(IF(B.status=3,1,0))
Pending
FROM (SELECT * FROM mine WHERE s_no=1) A LEFT JOIN detail B
ON A.s_no=B.s_no
GROUP BY A.s_no, A.name, a.lname;

以下是 SQL Fiddle Demo