所以我有4张表通过外键连接,即结果,位置,学生,候选人
我需要实现的是: 输出:
------------------------
s_fname | count(c_id)
-----------------------
Mark | 2 -> President
France| 2 -> President
..计算c_id在表格中重复了多少次"结果"这也是由"候选人"中的pos_id过滤的。表
以下是我的代码,缺少计数部分:
select s_fname
from results, candidates, student, positioning
where results.c_id = candidates.c_id
AND student.sid = results.sid
AND candidates.pos_id = positioning.pos_id
AND positioning.pos_id = 1
Group BY results.sid;
..我知道它缺少很多东西......
由于
对我而言似乎非常复杂,但我知道这里有大师可以实现这一目标,
结果表
---------------------
| r_id | sid | c_id |
---------------------
1 | 1 | 1
2 | 1 | 2
3 | 1 | 4
4 | 2 | 1
5 | 2 | 2
6 | 2 | 4
7 | 3 | 3
8 | 3 | 2
9 | 5 | 3
10 | 5 | 2
----------------------
student table
----------------
| s_id| s_fname|
----------------
1 | Mark
2 | Jorge
3 | France
4 | James
--------------------
Candidates Table
------------------------
| c_id | sid | pos_id
------------------------
1 | 1 | 1
2 | 2 | 2
3 | 4 | 3
4 | 3 | 1
5 | 5 | 2
----------------------
positioning Table
-----------------------
| pos_id | po_name |
-----------------------
1 | President
2 | Vice President
3 | Secretary
4 | Treasurer
答案 0 :(得分:1)
这是未经测试的,但应该返回您的预期结果。
它的作用是加入相关foreign keys
上的所有表格,有效地提供了所有列的宽表格。然后,我们限制为candidates
位置运行的President
。由于group
上的count aggregate
我们group
,我们需要name
。 count
应该反映他们获得的投票数,因为one to many relationship
表格有result
。
SELECT s_fname, Count(*)
FROM studentTable st
INNER JOIN Candidates c On c.sid = st.s_ID
INNER JOIN positioning p on c.pos_ID = p.pos_ID
INNER JOIN results r on st.s_ID = r.s_ID
WHERE po_Name = "President"
GROUP BY s_Fname
由于对预期连接的误解,以下查询应显示适当的结果。
SELECT s_fname, Count(*)
FROM studentTable st
INNER JOIN Candidates c On c.sid = st.s_ID
INNER JOIN positioning p on c.pos_ID = p.pos_ID
INNER JOIN results r on c.c_ID = r.c_ID
WHERE po_Name = "President"
GROUP BY s_Fname
答案 1 :(得分:1)
SELECT s_fname AS [Student Name], COUNT(A.c_id) AS [Count], po_name AS [Position]
FROM results AS A INNER JOIN candidates AS B ON A.c_id=B.c_id
INNER JOIN student AS C ON A.sid=C.sid
INNER JOIN positioning AS D ON B.pos_id=D.pos_id
WHERE B.pos_id = 1
GROUP BY s_fname
答案 2 :(得分:1)
SELECT s.s_fname, COUNT(*), p.po_name
FROM students s
JOIN candidates c ON c.s_id = s.s_id
JOIN positioning p ON c.pos_id = p.pos_id
JOIN results r ON s.s_id = r.s_id
WHERE p.pos_id = 1
GROUP BY s.s_id