查看此解决方案:MySql Join three tables
我看到我可以通过这样的方式加入3个表:
select s.name "Student", c.name "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid
但似乎我只能从每个表中选择一个列?我需要连接3个表中的多个列,其中sys_visits是主表,其中userID = contrID(sys_users,sys_visits)和clientID = clientID(sys_client,sys_visits)
SELECT pid, clientID, contrID, serviceDate, serviceStart, serviceStop FROM sys_visits
SELECT userGroupID, userID, fname, lname FROM sys_users
SELECT clientID, clientFName, clientLName FROM sys_client ORDER BY clientLName ASC
我尝试了很多变化,似乎无法正确理解语法?
答案 0 :(得分:4)
改为使用ANSI SQL-92
格式的连接。
SELECT a.*, b.*, c.*
FROM sys_users a
INNER JOIN sys_visits b
ON a.userID = b.contrlD
INNER JOIN sys_client c
ON b.clientID = c.clientID
在查询中使用星号表示您正在从表中选择所有列。如果只想选择特定列,请在查询中明确声明列名称,例如:
SELECT a.userGroupID, a.userID, a.fname, a.lname,
b.*,
c.*
FROM sys_users a
INNER JOIN sys_visits b
ON a.userID = b.contrlD
INNER JOIN sys_client c
ON b.clientID = c.clientID
答案 1 :(得分:1)
您可以从表格中选择任意数量的列。
SELECT sv.pid, sv.clientID, sv.contrID, sv.serviceDate, sv.serviceStart, sv.serviceStop, su.userGroupID, su.userID, su.fname, su.lname, sc.clientFName, sc.clientLName
FROM sys_visits sv, sys_users su, sys_client sc
ORDER BY sc.clientLName ASC
使用JOINS
[推荐]
SELECT sv.pid, sv.clientID, sv.contrID, sv.serviceDate, sv.serviceStart, sv.serviceStop, su.userGroupID, su.userID, su.fname, su.lname, sc.clientFName, sc.clientLName FROM sys_visits sv
JOIN sys_users su ON su.userID = sv.contrID
JOIN sys_client sc ON sc.clientID = sv.clientID
ORDER BY sc.clientLName ASC
答案 2 :(得分:1)
想想你是否有三个表,例如
指定,资格,专业化和教师表。如果你想在教师表中加入三个表,其中包含teacher_id,teacher_name,designation_id, qualification_id,specialization_id,status等......SELECT t.name as teacher_name, d.name as designation_name, q.name as qualification_name, s.name as specialization_name FROM teachers t INNER JOIN designation d ON t.designation_id = d.id INNER JOIN qualification q ON t.qualification_id = q.id INNER JOIN specialization s ON t.specialization_id = s.id WHERE t.status = 1;