这两个查询会提供相同的结果吗?

时间:2018-02-07 13:48:20

标签: sql database

人口超过2000万的国家的城市(城市和国家是2个不同的表)

查询#1:

SELECT name 
FROM city
WHERE country_id IN (SELECT country_id 
                     FROM country
                     WHERE population > 20000000);

查询#2:

 SELECT name 
 FROM city 
 JOIN country 
 WHERE country.population > 20000000;

3 个答案:

答案 0 :(得分:2)

不,两者不能保证返回相同的结果。它们可能在您的数据库中执行,但您应该使用您真正想要的版本。

如果name在表格中重复,则JOIN版本可以返回重复的行。

此外,您还没有限定列名,因此您可能会在@MockBean protected FileserverClient fileserverClient; @Before public void initMockBeans(){ given(fileserverClient.createFrom64(any(File64.class))) .willReturn(FileCreatorForTest.createFile()); } 的查询中遇到2018-02-07 14:52:58.325 WARN 22665 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'retryableRibbonLoadBalancingHttpClient' defined in org.springframework.cloud.netflix.ribbon.apache.HttpClientRibbonConfiguration: Unsatisfied dependency expressed through method 'retryableRibbonLoadBalancingHttpClient' parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ribbonLoadBalancer' defined in org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.loadbalancer.ILoadBalancer]: Factory method 'ribbonLoadBalancer' threw exception; nested exception is com.ecwid.consul.transport.TransportException: org.apache.http.conn.HttpHostConnectException: Connect to localhost:8500 [localhost/127.0.0.1] failed: Connexion refusée (Connection refused) 2018-02-07 14:52:58.333 ERROR 22665 --- [ main] o.z.p.spring.web.advice.AdviceTrait : Internal Server Error 错误。

答案 1 :(得分:0)

是的,但您需要明确加入条件

SELECT city.name
  FROM city
       JOIN country ON country. country_id = city.country_id
 WHERE country.population > 20000000

请注意,虽然两个查询选择相同的数据,但它们不是“相同”:一个可能比另一个快得多(取决于您的实际数据,索引和您使用的RDBMS)。

编辑:如果您正在计算SQL,那么考虑citycountry交换时两个查询会做什么可能会很有意思(即:获取city.population&gt的国家/地区) ;一些数字)

答案 2 :(得分:0)

正如我所知道的SQL,你应该稍微改变第二个查询:

SELECT name 
FROM city 
INNER JOIN country ON city.country_id = country.country_id 
WHERE ...