sql—在mysql中使用联接从多个表中选择数据

ca1c2owp  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(277)

我有下列表格
用户:


* 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

我需要找到与一个号码相关的所有帐户
我需要名称,用户名,roleid,courseid,corsename,staffid,通过提供移动
我已经写了这个查询,但是它返回零结果

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'

限制0,30

kokeuurv

kokeuurv1#

try联合运算符:

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 = ?;
00jrzges

00jrzges2#

对于courses表,我将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 = ?

相关问题