简体   繁体   English

SQL 中的 where 子句条件

[英]where clause conditions in SQL

Below is a join based on where clause:下面是一个基于 where 子句的连接:

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我一直在从在线资源中学习 SQL 并尝试使用连接进行转换

Two issues:两个问题:

  • The original query is confusing.原始查询令人困惑。 The outer joins (with the (+) suffix) are made irrelevant by the last where condition.外部连接(带有(+)后缀)与最后一个where条件无关。 Because of that condition, the query should only return records where there is an actual matching c record.由于这种情况,查询应该只返回存在实际匹配c记录的记录。 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.您的查询加入了TEST_TABLE3两次,而第一个查询只加入了一次,并且有两个条件决定了它是如何加入的。 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.顺便说一句,令人惊讶的是 SQL Fiddle 站点没有显示错误,因为两次使用相同的别名是没有意义的。 See for example how MySQL returns the error with the same query on dbfiddle (on all available versions of MySQL):例如,请参阅 MySQL 如何使用dbfiddle上的相同查询返回错误(在所有可用版本的 MySQL 上):

Not unique table/alias: 'C'不是唯一的表/别名:'C'

So to get the same result using the standard join notation, all joins should be inner joins:因此,要使用标准join表示法获得相同的结果,所有连接都应该是inner连接:

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. @tricot 正确地指出,拥有 2 个具有相同名称的别名并且没有出现错误是很奇怪的。 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.另外,回答您的问题:在第一个查询中,我们首先通过指定所有表名来在所有 3 个表之间执行交叉连接 After that, we are filtering the rows using the condition specified in the WHERE clause on output that we got after performing cross join.之后,我们使用执行交叉连接后得到的 output 上的WHERE子句中指定的条件过滤行。 In second query , you need to join test_table3 only once.第二个查询中,您只需加入test_table3一次。 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:由于现在您拥有所有必需的别名 A、B、C,就像在第一个查询中一样,因此您可以在最后一次连接后指定 2 个条件,如下所示:

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;

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

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