Precautions for the combined use of AND and OR in mysql conditional query!

The use of AND and OR is often used in mysql queries, but if it is written incorrectly, it will often have the opposite effect. No, I encountered it a few days ago, and the final test really raised a bunch of bugs!!!!

 

Without further ado, here are the main points:

1. When AND OR appears in the WHERE statement of mysql, AND is placed in front of OR, and the AND condition after OR will not work. Refer to sql:

SELECT
	e.total_amount
FROM
	cmo_expense_account e
WHERE
	e.project_id='236aec01d88e48cdaaee357a870d18b5'
	AND	e.ea_type =1
	OR (e.project_id  in (select t1.id from pm_project t1 where t1.parent_id='236aec01d88e48cdaaee357a870d18b5'))
	and e.total_amount>300

  Of course, the result must be 200 will also appear, if you put AND e.ea_type =1 and then put it later, naer_type=2 will also appear,

2. If you are afraid of making mistakes, you can use union all

Separate and and or, so that there will be no problem, but it is more troublesome,

                select sum(t3.total_amount) from   (
                SELECT
                    e.total_amount
                FROM
                    cmo_expense_account e
                WHERE e.project_id='236aec01d88e48cdaaee357a870d18b5'
                AND    e.ea_type =1

                union  ALL
                
                SELECT
                    e.total_amount
                FROM
                    cmo_expense_account e
                WHERE e.project_id in (select t1.id from pm_project t1 where t1.parent_id='236aec01d88e48cdaaee357a870d18b5')
                AND    e.ea_type =1)  t3

3. If you insist on putting AND after OR, then both sides of OR should be enclosed in () and juxtaposed with AND

For example this one:

SELECT * from student WHERE id = 1 or id = 2 AND age = 20;

If the id is 1 or 2 and the age is 20, the result is obvious:

The above query is for id=1 or id 2 and age 20. If you want to take a unique union, you need to write this

SELECT * from student WHERE (id = 1 or id = 2 ) AND age = 20;

In this way, the id is 1 or 2 and the age must be 20!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324855280&siteId=291194637