Maison base de données tutoriel mysql Keeping your data work on the server using UNION_MySQL

Keeping your data work on the server using UNION_MySQL

May 31, 2016 am 08:46 AM

I have found myself using UNION in MySQL more and more lately. In this example, I am using it to speed up queries that are using IN clauses. MySQL handles the IN clause like a big OR operation. Recently, I created what looks like a very crazy query using UNION, that in fact helped our MySQL servers perform much better.

With any technology you use, you have to ask yourself, "What is this tech good at doing?" For me, MySQL has always been excelent at running lots of small queries that use primary, unique, or well defined covering indexes. I guess most databases are good at that. Perhaps that is the bare minimum for any database. MySQL seems to excel at doing this however. We had a query that looked like this:

select category_id, count(*) from some_table<br>where<br>article_id in (1,2,3,4,5,6,7,8,9) and<br>category_id in (11,22,33,44,55,66,77,88,99) and<br>some_date_time > now() - interval 30 day<br>group by<br>category_id
Copier après la connexion

There were more things in the where clause. I am not including them all in these examples. MySQL does not have a lot it can do with that query. Maybe there is a key on the date field it can use. And if the date field limits the possible rows, a scan of those rows will be quick. That was not the case here. We were asking for a lot of data to be scanned. Depending on how many items were in the in clauses, this query could take as much as 800 milliseconds to return. Our goal at DealNews is to have all pages generate in under 300 milliseconds. So, this one query was 2.5x our total page time.

In case you were wondering what this query is used for, it is used to calculate the counts of items in sub categories on our category navigation pages. On this page it's the box on the left hand side labeled "Category". Those numbers next to each category are what we are asking this query to return to us.

Because I know how my data is stored and structured, I can fix this slow query. I happen to know that there are many fewer rows for each item for article_id than there is for category_id. There is also a key on this table on article_id and some_date_time. That means, for a single article_id, MySQL could find the rows it wants very quickly. Without using a union, the only solution would be to query all this data in a loop in code and get all the results back and reassemble them in code. That is a lot of wasted round trip work for the application however. You see this pattern a fair amount in PHP code. It is one of my pet peeves. I have written before about keeping the data on the server . The same idea applies here. I turned the above query into this:

select category_id, sum(count) as count from <br>(<br>	(<br>		select category_id, count(*) as count from some_table<br>		where<br>			article_id=1 and<br>			category_id in (11,22,33,44,55,66,77,88,99) and<br>			some_date_time > now() - interval 30 day<br>		group by<br>			category_id<br>	)<br>	union all<br>	(<br>		select category_id, count(*) as count from some_table<br>		where<br>			article_id=2 and<br>			category_id in (11,22,33,44,55,66,77,88,99) and<br>			some_date_time > now() - interval 30 day<br>		group by<br>			category_id<br>	)<br>	union all<br>	(<br>		select category_id, count(*) as count from some_table<br>		where<br>			article_id=3 and<br>			category_id in (11,22,33,44,55,66,77,88,99) and<br>			some_date_time > now() - interval 30 day<br>		group by<br>			category_id<br>	)<br>	union all<br>	(<br>		select category_id, count(*) as count from some_table<br>		where<br>			article_id=4 and<br>			category_id in (11,22,33,44,55,66,77,88,99) and<br>			some_date_time > now() - interval 30 day<br>		group by<br>			category_id<br>	)<br>	union all<br>	(<br>		select category_id, count(*) as count from some_table<br>		where<br>			article_id=5 and<br>			category_id in (11,22,33,44,55,66,77,88,99) and<br>			some_date_time > now() - interval 30 day<br>		group by<br>			category_id<br>	)<br>	union all<br>	(<br>		select category_id, count(*) as count from some_table<br>		where<br>			article_id=6 and<br>			category_id in (11,22,33,44,55,66,77,88,99) and<br>			some_date_time > now() - interval 30 day<br>		group by<br>			category_id<br>	)<br>	union all<br>	(<br>		select category_id, count(*) as count from some_table<br>		where<br>			article_id=7 and<br>			category_id in (11,22,33,44,55,66,77,88,99) and<br>			some_date_time > now() - interval 30 day<br>		group by<br>			category_id<br>	)<br>	union all<br>	(<br>		select category_id, count(*) as count from some_table<br>		where<br>			article_id=8 and<br>			category_id in (11,22,33,44,55,66,77,88,99) and<br>			some_date_time > now() - interval 30 day<br>		group by<br>			category_id<br>	)<br>	union all<br>	(<br>		select category_id, count(*) as count from some_table<br>		where<br>			article_id=9 and<br>			category_id in (11,22,33,44,55,66,77,88,99) and<br>			some_date_time > now() - interval 30 day<br>		group by<br>			category_id<br>	)<br>) derived_table<br>group by<br>	category_id
Copier après la connexion
Pretty gnarly looking huh? The run time of that query is 8ms. Yes, MySQL has to perform 9 subqueries and then the outer query. And because it can use good keys for the subqueries, the total execution time for this query is only 8ms. The data comes back from the database ready to use in one trip to the server. The page generation time for those pages went from a mean of 213ms with a standard deviation of 136ms to a mean of 196ms and standard deviation of 81ms. That may not sound like a lot. Take a look at how much less work the MySQL servers are doing now.mysql graph showing decrease in rows read

The arrow in the image is when I rolled the change out. Several other graphs show the change in server performance as well.

The UNION is a great way to keep your data on the server until it's ready to come back to your application. Do you think it can be of use to you in your application?

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment modifier une table dans MySQL en utilisant l'instruction ALTER TABLE? Comment modifier une table dans MySQL en utilisant l'instruction ALTER TABLE? Mar 19, 2025 pm 03:51 PM

L'article discute de l'utilisation de l'instruction ALTER TABLE de MySQL pour modifier les tables, notamment en ajoutant / abandon les colonnes, en renommant des tables / colonnes et en modifiant les types de données de colonne.

Comment configurer le cryptage SSL / TLS pour les connexions MySQL? Comment configurer le cryptage SSL / TLS pour les connexions MySQL? Mar 18, 2025 pm 12:01 PM

L'article discute de la configuration du cryptage SSL / TLS pour MySQL, y compris la génération et la vérification de certificat. Le problème principal est d'utiliser les implications de sécurité des certificats auto-signés. [Compte de caractère: 159]

Comment gérez-vous les grands ensembles de données dans MySQL? Comment gérez-vous les grands ensembles de données dans MySQL? Mar 21, 2025 pm 12:15 PM

L'article traite des stratégies pour gérer de grands ensembles de données dans MySQL, y compris le partitionnement, la rupture, l'indexation et l'optimisation des requêtes.

Quels sont les outils de GUI MySQL populaires (par exemple, MySQL Workbench, PhpMyAdmin)? Quels sont les outils de GUI MySQL populaires (par exemple, MySQL Workbench, PhpMyAdmin)? Mar 21, 2025 pm 06:28 PM

L'article traite des outils de GUI MySQL populaires comme MySQL Workbench et PhpMyAdmin, en comparant leurs fonctionnalités et leur pertinence pour les débutants et les utilisateurs avancés. [159 caractères]

Comment déposez-vous une table dans MySQL à l'aide de l'instruction TABLE DROP? Comment déposez-vous une table dans MySQL à l'aide de l'instruction TABLE DROP? Mar 19, 2025 pm 03:52 PM

L'article discute de la suppression des tables dans MySQL en utilisant l'instruction TABLE DROP, mettant l'accent sur les précautions et les risques. Il souligne que l'action est irréversible sans sauvegardes, détaillant les méthodes de récupération et les risques potentiels de l'environnement de production.

Expliquez les capacités de recherche en texte intégral InNODB. Expliquez les capacités de recherche en texte intégral InNODB. Apr 02, 2025 pm 06:09 PM

Les capacités de recherche en texte intégral d'InNODB sont très puissantes, ce qui peut considérablement améliorer l'efficacité de la requête de la base de données et la capacité de traiter de grandes quantités de données de texte. 1) INNODB implémente la recherche de texte intégral via l'indexation inversée, prenant en charge les requêtes de recherche de base et avancées. 2) Utilisez la correspondance et contre les mots clés pour rechercher, prendre en charge le mode booléen et la recherche de phrases. 3) Les méthodes d'optimisation incluent l'utilisation de la technologie de segmentation des mots, la reconstruction périodique des index et l'ajustement de la taille du cache pour améliorer les performances et la précision.

Comment représentez-vous des relations en utilisant des clés étrangères? Comment représentez-vous des relations en utilisant des clés étrangères? Mar 19, 2025 pm 03:48 PM

L'article discute de l'utilisation de clés étrangères pour représenter les relations dans les bases de données, en se concentrant sur les meilleures pratiques, l'intégrité des données et les pièges communs à éviter.

Comment créez-vous des index sur les colonnes JSON? Comment créez-vous des index sur les colonnes JSON? Mar 21, 2025 pm 12:13 PM

L'article discute de la création d'index sur les colonnes JSON dans diverses bases de données comme PostgreSQL, MySQL et MongoDB pour améliorer les performances de la requête. Il explique la syntaxe et les avantages de l'indexation des chemins JSON spécifiques et répertorie les systèmes de base de données pris en charge.

See all articles