如何从多个列中计算记录

时间:2018-06-26 21:52:15

标签: mysql

如何从多个列中写入计数mysql查询。我在所有表中都具有UID,因此我将查询框成这样,这样可以完成工作,但是有更好的方法来编写多个计数查询

SELECT
  (SELECT count(*)  from follow WHERE followed_user_uid = 'b4eb3820-1fc6-11e8-aead-23ee40fdc27f') as following,
  (SELECT count(*)  from follow WHERE  my_user_uid= 'b4eb3820-1fc6-11e8-aead-23ee40fdc27f') as followers,
  SUM(
      (SELECT count(*) from prac_test where UID = 'b4eb3820-1fc6-11e8-aead-23ee40fdc27f') +
      (select count(*) from multi_test where my_UID = 'b4eb3820-1fc6-11e8-aead-23ee40fdc27f') +
      (select count(*) from shadow_test where UID = 'b4eb3820-1fc6-11e8-aead-23ee40fdc27f')
  ) as totalTestCount;

1 个答案:

答案 0 :(得分:1)

SELECT * FROM
    (SELECT 
        (SELECT count(*)  from follow AS flw WHERE flw.followed_user_uid = param.user_id) as following,
        (SELECT count(*)  from follow AS flw WHERE flw.my_user_uid= param.user_id) as followers,
        SUM(
          (SELECT count(*) from prac_test AS pt where pt.UID = param.user_id) +
          (select count(*) from multi_test AS mt where mt.my_UID = param.user_id) +
          (select count(*) from shadow_test AS st where st.UID = param.user_id)
        ) AS totalTestCount
    FROM
        (SELECT
                'b4eb3820-1fc6-11e8-aead-23ee40fdc27f') AS user_id,
        ) AS param
    )AS tmp;