我有以下表格
用户:
* id
* name
* role id
* phone
学生
1: userid ( fk users.id)
2: course_id
工作人员
1: staff_id(fk users.id)
2: course-id
课程
1: COURSE_ID
1:COURSENAME
我需要找到与数字关联的所有帐户
我需要通过提供手机来输入姓名,用户名,角色,课程ID,科目名称,员工姓名
我已经编写了此查询,但是返回的结果为零
SELECT users.name, users.id, staff.user_id, students.course_id, users.role_id, courses.course_title FROM users INNER JOIN students ON users.id = students.user_id INNER JOIN staff ON staff.user_id = users.id INNER JOIN courses ON courses.id = students.course_id WHERE users.phone = '9495990028'
LIMIT 0,30
答案 0 :(得分:2)
尝试使用 union 运算符:
SELECT name, s.userid, roleid, s.course_id, c.coursename, null
FROM USERS u
INNER JOIN STUDENTS s
INNER JOIN COURSES c
ON s.userid = u.id AND c.course_id = s.course_id
WHERE u.phone = ?
UNION
SELECT name, null, roleid, s.course_id, c.coursename, s.staff_id
FROM USERS u
INNER JOIN STAFF s
INNER JOIN COURSES c
ON s.staff_id = u.id AND c.course_id = s.course_id
WHERE u.phone = ?;
答案 1 :(得分:0)
对于COURSES表,我使用来自学生和教职员工的course_id来检查ID
SELECT name, s.userid, roleid, s.course_id, c.coursename, st.staff_id
FROM USERS u
INNER JOIN STUDENTS s ON s.userid = u.id
INNER JOIN STAFF st ON st.staff_id = u.id
INNER JOIN COURSES c ON c.course_id = s.course_id AND c.course_id = st.course_id
WHERE u.phone = ?