Differences between exists replacement in SQL

Source: Internet
Author: User

When using exists in SQL to replace in queries, note that when using exists, you must associate the primary query with the subquery. Otherwise, the query will not receive the following results:
Statement 1 use in to query:
Select realname from users where users. userid in
(Select gallery. galleries. creatorid from gallery. galleries group by gallery. galleries. creatorid
Having count (gallery. galleries. creatorid)> 1) Order by userid
Statement 2 Use exists to query:
Select realname from users where exists
(Select gallery. galleries. creatorid from gallery. galleries group by gallery. galleries. creatorid
Having count (gallery. galleries. creatorid)> 1) Order by userid
At first glance, there is no error, but Statement 2 forgets the association between the primary key of the primary query and the subquery, so that all the content of the primary query can be found out.
Statement 2 should be written correctly:
Select * From gallery. galleries as a where exists (select a. creatorid from gallery. galleries as B
Where a. creatorid = B. creatorid group by B. creatorid having count (B. creatorid)> 1) Order by creatorid
Note: exists is a Boolean operation. As long as the word query result set has a data result, the where condition is true, so the second query statement is equivalent
Select realname from users where 1 = 1 order by userid (if a piece of data is found in the subquery)

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.