简体   繁体   中英

Compare a table with itrself in SQL?

The output of below query is:

query:

SELECT CategoryID
FROM Categories
WHERE EXISTS (SELECT CategoryID FROM Categories as c WHERE c.CategoryID < Categories.CategoryID);

Output:

2
3
4

Table Categories:

CategoryID  CategoryName
1           Beverages
2           Condiments
3           Confections
4           Dairy Products

I wanna trace sub query (SELECT CategoryID FROM Categories as c WHERE c.CategoryID < Categories.CategoryID) . Do records compare one by one? Why does not the ID 1 come out on the output?

EXISTS is used for the existence of any record in a subquery.

when you use SELECT CategoryID FROM Categories as c WHERE c.CategoryID < Categories.CategoryID

there isn't match any row from CategoryID = 1

If you want to get CategoryID = 1

try to use

c.CategoryID <= Categories.CategoryID

instead of

c.CategoryID < Categories.CategoryID

to contain CategoryID = 1 row.

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