至少从图书馆或图书馆 2 借过一本书的两个 table 之间的唯一学生 ID
Unique Student id Count between Two table who borrowed at least one books from Library1 or Library 2
我需要计算至少从图书馆 1 或图书馆 2 借过 1 本书的学生总数。
Students table:
id | name
---------
1 A
2 B
3 C
4 D
5 E
Library1 table:
id | student_id | book_id
-------------------------
1 1 2
2 1 3
3 2 3
Library2 table:
id | student_id | book_id
-------------------------
1 3 2
2 1 1
3 2 2
从上面的表格预期结果总计 = 3
使用 Laravel 数据库查询或 MySQL.
帮助我解决这个问题
对表和聚合的 student_id
使用 UNION
(删除重复项):
SELECT COUNT(*)
FROM (
SELECT student_id FROM Library1
UNION
SELECT student_id FROM Library2
) t
或者,UNION ALL
(returns 重复)并计算不同的 student_id
s:
SELECT COUNT(DISTINCT student_id)
FROM (
SELECT student_id FROM Library1
UNION ALL
SELECT student_id FROM Library2
) t
我需要计算至少从图书馆 1 或图书馆 2 借过 1 本书的学生总数。
Students table:
id | name
---------
1 A
2 B
3 C
4 D
5 E
Library1 table:
id | student_id | book_id
-------------------------
1 1 2
2 1 3
3 2 3
Library2 table:
id | student_id | book_id
-------------------------
1 3 2
2 1 1
3 2 2
从上面的表格预期结果总计 = 3
使用 Laravel 数据库查询或 MySQL.
帮助我解决这个问题对表和聚合的 student_id
使用 UNION
(删除重复项):
SELECT COUNT(*)
FROM (
SELECT student_id FROM Library1
UNION
SELECT student_id FROM Library2
) t
或者,UNION ALL
(returns 重复)并计算不同的 student_id
s:
SELECT COUNT(DISTINCT student_id)
FROM (
SELECT student_id FROM Library1
UNION ALL
SELECT student_id FROM Library2
) t