0

我有一个包含列的用户表:user_id, teacher_id1, teacher_id2, teacher_id3

带 id 的教师表

每个用户可以有相同的 idteacher_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}' ";
4

2 回答 2

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;
于 2013-05-16T14:36:27.057 回答
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

SQL 小提琴

| ID | COUNT(*) |
-----------------
|  1 |        2 |
|  2 |        3 |
|  3 |        2 |
于 2013-05-16T12:46:16.353 回答