简体   繁体   中英

adding a where clause on an inner join

I have 2 tables : registered_students - cols: regnum AND student - cols: regnum, name

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. 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%'

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. You could try the following if the above does not work:

  • case insensitive matching, eg WHERE LOWER(registered_students.regnum) LIKE 'reg4%'
  • LEFT JOIN if you want the data from either of these tables

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%';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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