在两个连接的表中选择一对多的关系

时间:2018-03-29 00:36:16

标签: mysql sql select count

a16s            
id  pic     
1   1.jpg       
2   2.jpg       
3   3.jpg       
4   4.jpg       

a16s_like           
id  p_id u_id   approve
1   1       2   0
2   1       1   1
3   1       5   1
4   1       6   1
5   1       7   0
6   2       2   0
7   2       3   0
8   2       1   1
9   4       4   0
10  4       3   1
11  4       2   1


$sql="SELECT A.id, A.pic

(select count(*) from a16s_like B where B.p_id = A.id) AS Ashow, 
(select count(*) from a16s_like B where B.p_id = A.id and B.approve='0') AS Nshow,
(select count(*) from a16s_like B where B.p_id = A.id and B.approve='1') AS Yshow
FROM a16s A  ORDER BY id DESC";

我使用了三次批准的colume,可以用任何方法来雄辩地搜索seach吗? 我的目的是

当u_id = 2来执行select时,我想得到

id pic    Ashowocunt  approve_0_count  approve_1_count     u_id2_approve   
1  1.jpg   5          2                3                   0
2  2.jpg   3          2                1                   0
3  3.jpg   0          0                0                   null
4. 4.jpg   3          0                3                   0

U_ID = 3

id pic    Ashowocunt  approve_0_count  approve_1_count     u_id3_approve   
1  1.jpg   0          0                0                   null
2  2.jpg   0          1                0                   0
3  3.jpg   0          0                0                   null
4. 4.jpg   1          0                1                   1    

需要显示变量u_id的所有a.id,就像u_id = 2或u_id = 3(有空)

1 个答案:

答案 0 :(得分:1)

你可以试试这个。

使用CASE express和FULL OUTER JOIN

但Mysql不支持FULL OUTER JOIN,因此您需要使用LEFT JOINRight JOIN来制作它。

SELECT 
    A.id, 
    A.PIC, 
    SUM(CASE WHEN  B.approve IS NULL THEN 0 ELSE 1 END) AS Ashowocunt,
    SUM(CASE WHEN  B.approve=0 THEN 1 ELSE 0 END) AS Nshow,
    SUM(CASE WHEN  B.approve=1 THEN 1 ELSE 0 END) AS Yshow
FROM  
(
  SELECT A.id ID
  FROM  a16s AS A
  LEFT JOIN a16s_like  AS B ON A.ID = B.p_id 
  UNION 
  SELECT B.p_id ID
  FROM  a16s AS A
  RIGHT JOIN a16s_like  AS B ON A.ID = B.p_id 
) AS T
LEFT JOIN a16s AS A ON A.ID = T.ID
LEFT JOIN a16s_like  AS B ON T.ID = B.p_id 
GROUP BY A.id,A.PIC 

修改

您可以在a16s_like

上使用子查询
SELECT 
    A.id, 
    A.PIC, 
    SUM(CASE WHEN  B.approve IS NULL THEN 0 ELSE 1 END) AS Ashowocunt,
    SUM(CASE WHEN  B.approve=0 THEN 1 ELSE 0 END) AS Nshow,
    SUM(CASE WHEN  B.approve=1 THEN 1 ELSE 0 END) AS Yshow
FROM  
(
  SELECT A.id ID
  FROM  a16s AS A
  LEFT JOIN a16s_like  AS B ON A.ID = B.p_id 
  UNION 
  SELECT B.p_id ID
  FROM  a16s AS A
  RIGHT JOIN a16s_like  AS B ON A.ID = B.p_id 
) AS T
LEFT JOIN a16s AS A ON A.ID = T.ID
LEFT JOIN 
(
SELECT * 
FROM  a16s_like
WHERE u_id=2
)  AS B ON T.ID = B.p_id 
GROUP BY A.id,A.PIC 

另一方面,您可以在B.approve=1 AND B.u_id=2快递

上设置CASE
SUM(CASE WHEN  B.approve=1 AND B.u_id=2 THEN 1 ELSE 0 END) AS Yshow 

SQLFiddle