简体   繁体   中英

SQL Query HELP - Nested I think

I am writing an SQL statement which needs to:

  1. Look for a job with a certain number
  2. Match that job to another table
  3. Show the results

This is what I currently have.

select * from PreviousJobs pj, Jobs j where jobId = '273121' 
AND where (pj.sOtherRef = j.sOtherRef) = True    

Hmmmmm

You don't need the =True, or the second where.

Just

select * from PreviousJobs pj, Jobs j where jobId = '273121' 
AND pj.sOtherRef = j.sOtherRef 

There's no nesting needed; it is a simple JOIN that's required, and that would be best written with the explicit join notation:

SELECT cj.*, pj.* 
  FROM PreviousJobs AS pj
  JOIN Jobs         AS cj ON pj.sOtherRef = cj.sOtherRef
 WHERE cj.jobId = '273121' 

You don't need the second WHERE in your statement (that is a syntax error; you should have supplied us with the error message(s) that your DBMS gave you). You don't need to compare the comparison with TRUE.

The comma-separated list of table names in the FROM clause was necessary in SQL-86 and SQL-89, but has not been necessary since SQL-92 support was added into the DBMS. You should know about it so that if you get to read old SQL, you know what it means. But you should plan to use only the new JOIN notation unless there's overwhelming (and ill-advised) pressure from workplace standards to use the old notation.

Depending on the DBMS you use, you might find the AS in the table aliases is not permitted (Oracle), even though the standard says it is OK. That sort of difference is why it is a good idea to include information about your DBMS in the question.

  1. Look for a job with a certain number : where jobId = '273121'
  2. Match that job to another table : inner join on pj.sOtherRef = j.sOtherRef
  3. Show the results : select * from PreviousJobs pj

The query will be..

select *
  from PreviousJobs pj inner join Jobs j ON pj.sOtherRef = j.sOtherRef
 where j.jobId = '273121'

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