在SQL Server中使用多个NOT IN(Using multiple NOT IN in SQL Server)

编程入门 行业动态 更新时间:2024-10-09 05:25:59
在SQL Server中使用多个NOT IN(Using multiple NOT IN in SQL Server)

我有两个这样的表格:

表1: City - 主键: ID_City :

| City | ID_City | ID_State| +-----------+---------+---------+ | Chennai | 1 | 2 | | Bengaluru | 2 | 1 | | Lucknow | 3 | 3 | | . | . | . | | . | . | . |

而且,我正在使用NOT IN检查现有城市的同时将新城市添加到现有数据库。 @table看起来像这样:

表1: @table

| City | ID_State|Zip_Code| +-----------+---------+--------+ | Chennai | 2 |00001 | | Chennai | 2 |00002 | | Chennai | 2 |00003 | | Bengaluru | 1 |10011 | | Bengaluru | 1 |10012 | | Bengaluru | 1 |10013 | | Lucknow | 3 |20001 | | Mysore | 4 |50001 | | Mysore | 4 |50002 | | Mysore | 4 |50003 | | . | . | . |

预期结果:

查询应该检查已经存在的城市,并过滤掉这些,不应该添加。 (这是用NOT IN完成的)

另外,如果有多个相同城市的行,则不应该添加相同城市的多个副本。 例如:查询应该只添加一行City-'Mysore'而不是三行

我执行的查询:

SELECT City, id_state FROM @table WHERE City NOT IN (SELECT City FROM City WHERE City IS NOT NULL) AND id_state NOT IN (SELECT id_state FROM City WHERE id_state IS NOT NULL)

I've two tables like this:

Table 1: City - primary key: ID_City:

| City | ID_City | ID_State| +-----------+---------+---------+ | Chennai | 1 | 2 | | Bengaluru | 2 | 1 | | Lucknow | 3 | 3 | | . | . | . | | . | . | . |

And I'm adding new cities to an existing database while checking for already existing cities using NOT IN. The @table looks like this:

Table 1: @table

| City | ID_State|Zip_Code| +-----------+---------+--------+ | Chennai | 2 |00001 | | Chennai | 2 |00002 | | Chennai | 2 |00003 | | Bengaluru | 1 |10011 | | Bengaluru | 1 |10012 | | Bengaluru | 1 |10013 | | Lucknow | 3 |20001 | | Mysore | 4 |50001 | | Mysore | 4 |50002 | | Mysore | 4 |50003 | | . | . | . |

Expected result:

The query should check for City that are already there and filter out those and should not add. (This is done using NOT IN)

Also, it should not add multiple copies of same cities if there are multiple rows of same cities. For example: The query should add only one row of City- 'Mysore' and not three rows

Query I executed:

SELECT City, id_state FROM @table WHERE City NOT IN (SELECT City FROM City WHERE City IS NOT NULL) AND id_state NOT IN (SELECT id_state FROM City WHERE id_state IS NOT NULL)

最满意答案

一个城市名称可以属于多个州,因此您需要检查两个组合。

我觉得下面的查询应该给你想要的输出。

SELECT DISTINCT City, id_state FROM @table T1 WHERE NOT EXISTS ( SELECT 1 FROM City C WHERE C.City = T1.City AND T.id_state = C.id_state )

One city name can belong to multiple states, so you need to check for both the combinations.

I feel following query should give you desired output.

SELECT DISTINCT City, id_state FROM @table T1 WHERE NOT EXISTS ( SELECT 1 FROM City C WHERE C.City = T1.City AND T.id_state = C.id_state )

更多推荐

本文发布于:2023-07-27 04:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1284861.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   SQL   Server   multiple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!