简体   繁体   中英

where clause conditions in SQL

Below is a join based on where clause:

SELECT a.* FROM TEST_TABLE1 a,TEST_TABLE2 b,TEST_TABLE3 c
WHERE a.COL11 = b.COL11
AND b.COL12 = c.COL12
AND a.COL3 = c.COL13;

I have been learning SQL from online resources and trying to convert it with joins

Two issues:

  • The original query is confusing. The outer joins (with the (+) suffix) are made irrelevant by the last where condition. Because of that condition, the query should only return records where there is an actual matching c record. So the original query is the same as if there were no such (+) suffixes.
  • Your query joins TEST_TABLE3 twice, while the first query only joins it once, and there are two conditions that determine how it is joined there. You should not split those conditions over two separate joins.

BTW, it is surprising that the SQL Fiddle site does not show an error, as it makes no sense to use the same alias twice. See for example how MySQL returns the error with the same query on dbfiddle (on all available versions of MySQL):

Not unique table/alias: 'C'

So to get the same result using the standard join notation, all joins should be inner joins:

SELECT * 
FROM  TEST_TABLE1 A
INNER JOIN  TEST_TABLE2 B
        ON A.COL11 = B.COL11
INNER JOIN TEST_TABLE3 C
        ON A.COL11 = B.COL11
        AND B.COL12 = C.COL12;

@tricot correctly pointed out that it's strange to have 2 aliases with the same name and not getting an error. Also, to answer your question: In the first query , we are firstly performing cross join between all the 3 tables by specifying all the table names. After that, we are filtering the rows using the condition specified in the WHERE clause on output that we got after performing cross join. In second query , you need to join test_table3 only once. Since now you have all the required aliases A,B,C as in the first query so you can specify 2 conditions after the last join as below:

SELECT A.* FROM  TEST_TABLE1 A
LEFT JOIN  TEST_TABLE2 B
ON A.COL11 = B.COL11
left join TEST_TABLE3 C
on B.COL12 =C.COL12 AND  A.COL3 = C.COL13;

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