简体   繁体   English

在MySQL中我可以在另一个表中将id FK与varchar进行比较

[英]in MySQL can I compare id FK with varchar in another table

I have table with courseID, studentName and the other table is courseID , courseName user will search for the course name in the student table based on the student name what sql syntax should I use ? 我有带有courseID,studentName的表,另一个表是courseID,courseName用户将根据学生名在学生表中搜索课程名,我应该使用哪种sql语法? join or inner join 连接或内部连接

You can try this: 您可以尝试以下方法:

select a.studentName,b.courseName 
from tbl_name a 
inner join tbl_name b
on a.courseID = b.courseID 

If you use JOIN and specify a constraint (eg on a.courseId = b.courseId ) it is exactly the same as if you use INNER JOIN , so according to your table structure you should do something like: 如果使用JOIN并指定约束(例如, on a.courseId = b.courseId ),则与使用INNER JOIN完全相同,因此根据表结构,您应该执行以下操作:

select * from studentTable
inner join courseTable 
on studentTable.courseID = courseTable.courseID
where studentTable.studentName = 'Jack Black';

In MySQL you could also write 在MySQL中,您还可以编写

select * from studentTable, courseTable 
where studentTable.courseID = courseTable.courseID
and studentName = 'Jack Black';

as it would internally be queried in the same way. 就像在内部以相同的方式查询一样。

Check out the exact syntax for joins here: http://dev.mysql.com/doc/refman/5.7/en/join.html 在此处查看连接的确切语法: http : //dev.mysql.com/doc/refman/5.7/en/join.html

You join when you are looking for a joined result, such as select all student names along with all their courses. 您在寻找合并结果时加入,例如选择所有学生姓名及其所有课程。 Eg: 例如:

select s.studentname, c.coursename
from course c
join student_takes_course s on s.courseid = c.courseid;

or (as the order of the tables doesn't matter): 或(因为表的顺序无关紧要):

select s.studentname, c.coursename
from student_takes_course s
join course c on s.courseid = c.courseid;

JOIN is just short for INNER JOIN . JOIN只是INNER JOIN缩写。 You can use either. 您可以使用。

But when you are not interested in the joined result, then it's a good habit not to join. 但是,如果您对合并结果不感兴趣,那么不加入是一个好习惯。 Such as when you simply want to show the course names from the course table, as in your example. 例如,当您仅想显示课程表中的课程名称时(如您的示例)。 You would then use IN or EXISTS usually: 然后,您通常会使用INEXISTS

select coursename 
from course
where courseid in 
(
  select courseid
  from student_takes_course
  where studentname = 'Joe'
);

or 要么

select c.coursename 
from course c
where exists
(
  select *
  from student_takes_course s
  where s.studentname = 'Joe'
  and s.courseid = c.courseid
);

(I prefer IN clauses over EXISTS clauses for their simplicity and use them when possible.) (我更喜欢IN子句而不是EXISTS子句,并尽可能使用它们。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM