The case comes from "The Way of MySQL Management"
not in subquery optimization
not in followed by a subquery
select
SQL_NO_CACHE count(*)
from
test1
where
id not in(
select
id
from
test2
)
Related queries with left join
select
SQL_NO_CACHE
from
test1
left join
test2
on
test1.id=test2.id
where test2.id is null
Using relational query is better than subquery
Match patterns like '%xxx%' optimized
'xxx%' can use index, '%xxx%' cannot use index, so try to use 'xxx%'.
If you must use index and fuzzy query, you can use the following example:
select
count(*)
from
artist a
join (
select
artist_id
from
artist
where
name like '%xxx%'
) b
on
a.artist_id=b.artist_id
Among them, artist_id is the index of the artist table
limit paging optimization
raw query
select
SQL_NO_CACHE *
from
test1
order by
id
limit 99999, 10
Although the above sql uses an index, the first row is located at row 99999, and the next 10 rows are scanned, which is equivalent to a full table scan.
The optimization is as follows:
select
SQL_NO_CACHE *
from
test1
where
id >= 100000
order by id
limit 10
In this way, the efficiency has been significantly improved.
There a way to optimize through the connection in the table.
select
SQL_NO_CACHE *
from
test1 a
join (
select
SQL_NO_CACHE *
from
test1 b
order by id
limit 99999,1
)b
on
a.id >= b.id
limit 10
First take out the one after 99999, and then take out the next 10, which can also improve the efficiency
How to optimize count(*)
- count(auxiliary index) is faster than count(*)
count(distinct) works better
- or Conditional Optimization
Ordinary use of or will not use the index, such as:
- or Conditional Optimization
select
*
from
test1
where
name='a'
or
age > 17
You can use union all optimizations:
select
*
from
test1
where
name='a'
union all
select
*
from
test1
where
age > 17
Such a query can use the index to speed up the query
ON DUPLICATE KEY UPDATE 用法
This is a very efficient primary key conflict processing judgment in mysql. If there is a conflict, execute update, and if there is no conflict, execute insert, such as:
insert into
gg
values
(
3,
'd'
)
ON DUPLICATE KEY UPDATE
id = id+1
This sql means that if the value of the primary key id 3 already conflicts when inserting data, then the 3 in the database will be updated to 4
Unnecessary sorting
Do not sort without sorting in subqueries
Unnecessary nested select query
Related query