我有一个包含列的用户表:user_id, teacher_id1, teacher_id2, teacher_id3
和
带有id的教师表
每个用户可以拥有teacher_id1, teacher_id2, teacher_id3
我想算一下有多少用户拥有同一位老师。
用户表
+----------------------------------------+
| user_Id teacher_id1 teacher_id2 teacher_id3 |
+----------------------------------------+
| 1 1 1 1 |
| 2 2 1 3 |
| 3 2 3 3 |
| 4 2 2 2 |
+----------------------------------------+
教师表
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
$ id1的计数是:2
$ id2的计数是:3
$ id3的计数是:2
我试过这样的事,但这不正确!
SELECT COUNT(*) FROM users WHERE concat_ws('',teacher_id1 OR teacher_id2
OR teacher_id3) like '{$id}' ";
答案 0 :(得分:1)
您有三个不同列中的数据。您需要将其合并为一列,以获得所需的不同计数。为此,您可以使用union all
。然后,计数只是count(distinct)
:
select teacher_id, COUNT(distinct USER_ID)
from ((select user_id, teacher_id1 as teacher_id
from t
) union all
(select user_id, teacher_id2
from t
) union all
(select user_id, teacher_id3
from t
)
) s
group by teacher_id;
答案 1 :(得分:0)
尝试此查询
select b.id, count(*)
from
tbl1 a
inner join
tbl2 b
on b.id = teacher_id1 or b.id = teacher_id2 or b.id = teacher_id3
group by b.id
| ID | COUNT(*) |
-----------------
| 1 | 2 |
| 2 | 3 |
| 3 | 2 |