MySQL SQL statements handle the order of operations for OR and and in parentheses

Source: Internet
Author: User

requirements, I want to retrieve the results of a =1 or b=1 and c = 0 or c=1

Example:

SELECT * FROM Test where a = 1 or b = 1 and (c = 0 or c = 1)

This retrieves the result set of A=1 or b=1, and then filters out the results of c=0 or c=1.

If we change the wording of the

SELECT * FROM Test where a = 1 or b = 1 and c = 0 or c = 1

This retrieves the result set of a=1 or B =1 or c=1, and then filters out the results of the c=0, which is not what I expected, so it is OK to adjust their processing order in parentheses.

First filter the same hospital or the same department of the user list, and then according to the number of medical said and the number of fans again filter the user list,

Correct sql:

SELECT a.* from Xm_user a WHERE (a.user_hospital = ' 301 Hospital ' or a.user_department = ' orthopedic ') and a.user_id! = 1
And not EXISTS (SELECT b.* from xm_user_friendship b WHERE b.fs_from_user_id = 1 and b.fs_to_user_id = a.user_id);

Error SQL:

SELECT a.* from Xm_user a WHERE a.user_hospital = ' 301 Hospital ' or a.user_department = ' orthopedic ' and a.user_id! = 1
And not EXISTS (SELECT b.* from xm_user_friendship b WHERE b.fs_from_user_id = 1 and b.fs_to_user_id = a.user_id);

MySQL SQL statements handle the order of operations for OR and and in parentheses

Related Article

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.