简体   繁体   English

在内部联接上添加where子句

[英]adding a where clause on an inner join

I have 2 tables : registered_students - cols: regnum AND student - cols: regnum, name 我有2个表: registered_students -cols:regnum和student -cols:regnum,名称

So I'm working on a query to select from both tables. 所以我正在研究从两个表中进行选择的查询。 It's working so far, but now I want to add a where clause to it, and it's not returning any rows. 到目前为止,它已经可以工作了,但是现在我想向其中添加一个where子句,并且它不返回任何行。 Here is the query 这是查询

SELECT registered_students.regnum
     , student.name
FROM registered_students
    INNER JOIN student ON registered_students.regnum=student.regnum

example data: 示例数据:

registered_students 1).reg3030 2). reg4032
              student 1).reg3030 John Doe 2).reg4032 Luke White

So I need to add a where clause like WHERE regnum LIKE 'reg4%' 因此,我需要添加一个WHERE regnum LIKE 'reg4%'类的WHERE regnum LIKE 'reg4%'子句,例如WHERE regnum LIKE 'reg4%'

You will have to specify the alias as the column has same name in both the tables, try the following query: 您将必须指定别名,因为这两个表中的列名称相同,请尝试以下查询:

SELECT registered_students.regnum, student.name 
FROM registered_students JOIN student ON registered_students.regnum=student.regnum
WHERE registered_students.regnum LIKE 'reg4%';

The output will also depend on the availability of data with reg4 in both the tables. 输出还将取决于两个表中带有reg4的数据的可用性。 You could try the following if the above does not work: 如果以上方法无效,您可以尝试以下方法:

  • case insensitive matching, eg WHERE LOWER(registered_students.regnum) LIKE 'reg4%' 不区分大小写的匹配,例如WHERE LOWER(registered_students.regnum) LIKE 'reg4%'
  • LEFT JOIN if you want the data from either of these tables 如果要从这两个表中的任何一个中获取数据,请LEFT JOIN

Update 更新资料

With the updated data, it might be because of whitespace or a dot in the beginning of the value, I would try the following: 对于更新的数据,可能是由于空格或值开头的点引起的,我将尝试以下操作:

SELECT registered_students.regnum, student.name 
FROM registered_students JOIN student ON TRIM(registered_students.regnum) = TRIM(student.regnum)
WHERE registered_students.regnum LIKE '%reg4%';

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

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