我有2个表(学生类和用户)
表studentclass
.method private hidebysig static char BitwiseOr(char c1,
char c2,
char c3,
char c4) cil managed
{
//
.maxstack 2
.locals init (char V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: or
IL_0004: ldarg.2
IL_0005: or
IL_0006: ldarg.3
IL_0007: or
IL_0008: call char [mscorlib]System.Convert::ToChar(int32)
IL_000d: stloc.0
IL_000e: br.s IL_0010
IL_0010: ldloc.0
IL_0011: ret
} // end of method Program::BitwiseOr
表用户
columns (id, class_name, user_schoolid_faculty, user_schoolid_student)
我的第一个问题是
columns (id, firstname, lastname, schoolid, position)
user_schoolid_faculty is a foreign key from schoolid
user_schoolid_student is a foreign key from schoolid
我想使用schoolid查看用户的名字和姓氏的数据
SELECT * FROM studentclass WHERE class_name = '$class_name'
它会引发我的错误,而不是唯一的表/别名'用户'
答案 0 :(得分:1)
对于同一个表user
,您应该使用不同的别名,当您使用JOIN
时,您应该使用ON
来合并两个表,而不是WHERE
,试试这个;)
SELECT studentclass.class_name, user1.firstname, user2.lastname
FROM studentclass
INNER JOIN user user1
ON studentclass.user_schoolid_faculty = user1.schoolid
AND user1.position = 'Faculty'
LEFT JOIN user user2
ON studentclass.user_schoolid_student = user2.schoolid
AND user2.position = 'Student'
还有一个不清楚的地方,为什么在此查询中使用一个INNER JOIN
和一个LEFT JOIN
?
答案 1 :(得分:1)
您必须为表使用别名:
SELECT studentclass.class_name, u1.firstname, u1.lastname
FROM studentclass
INNER JOIN user u1
ON studentclass.user_schoolid_faculty = u1.schoolid
WHERE user.position = 'Faculty'
LEFT JOIN user u2
ON studentclass.user_schoolid_student = u2.schoolid
WHERE u1.position = 'Student'
答案 2 :(得分:1)
对于SQL Server,使用方括号作为保留关键字user
还要为表添加别名。
SELECT SC.class_name, U1.firstname, U2.lastname
FROM studentclass SC
INNER JOIN [user] U1 ON SC.user_schoolid_faculty = U1.schoolid
LEFT JOIN [user] U2 ON SC.user_schoolid_student = U2.schoolid AND U2.position = 'Student'
WHERE U1.position = 'Faculty'
对于MySQL:
SELECT SC.class_name, U1.firstname, U2.lastname
FROM studentclass SC
INNER JOIN `user` U1 ON SC.user_schoolid_faculty = U1.schoolid
LEFT JOIN `user` U2 ON SC.user_schoolid_student = U2.schoolid AND U2.position = 'Student'
WHERE U1.position = 'Faculty'