Exist and not exist usage

Source: Internet
Author: User

Reference: http://wenku.baidu.com/view/577f4d49cf84b9d528ea7a6f.html // This lecture is very detailed

Reference from: http://chenling1018.blog.163.com/blog/static/14802542007112944944177/

-- Exists (SQL return result set, true)
-- Not exists (SQL does not return result set, true)
-- As follows:
 
-- Table
ID name
1 A1
2 A2
3 A3



-- Table B
Id aid name
1 1 B1
2 2 B2
3 2 B3



-- The relationship between table A and table B is 1-to-many. A. ID => B. Aid

Select ID, name from a where exist (select * from B where a. ID = B. Aid)
-- The execution result is
1 A1
2 A2



-- The cause can be analyzed as follows:
Select ID, name from a where exists (select * from B where B. Aid = 1)
---> Select * from B where B. Aid = 1 has a value and returns true, so data exists.

Select ID, name from a where exists (select * from B where B. Aid = 2)
---> Select * from B where B. Aid = 2 has a value and returns true, so data exists.

Select ID, name from a where exists (select * from B where B. Aid = 3)
---> Select * from B where B. Aid = 3 no value, returns false, so no data


-- Not exists is the opposite
Select ID, name from a where not exist (select * from B where a. ID = B. Aid)
-- The execution result is
3 A3



========================================================== ==========================================


-- Exists = In, meaning the same, but there is a little difference in syntax, it seems that the efficiency of using in is almost the same, it should be because the index will not be executed
Select ID, name from a where ID in (select aid from B)


-- Not exists = not in, meaning the same, but there is a little difference in syntax
Select ID, name from a where id not in (select aid from B)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.