简体   繁体   中英

SQL exercise: help needed

Invent a test exercise so you can help me:

We have two tables that are the following:

table1:

id: auto_increment (primary key)
number_complete: varchar(255)

table2:

id: auto_increment (primary key)
name: varchar(255)
number_cut: varchar(255)

We have this data in each table:

table1:

在此处输入图片说明

table2:

在此处输入图片说明

well really in table 1 there are more than one million records and in the second table there are 34 thousand records.

the result I'm looking for is something like this:

在此处输入图片说明

What he was executing and continues to execute was this sentence:

select t2.name, count(t1.id) 
from table1 as t1, table2 as t2
where t1.number_complete like concat(t2.number_cut,'%')
group by t2.name;

But at this moment I've been waiting almost 1 hour for the sentence to be executed, as you may realize I am not an expert in SQL.

Add an index on number_complete .

ALTER TABLE table1
ADD INDEX (number_complete);

Since indexes are B-trees by default, this makes matching prefixes reasonably efficient, and LIKE is able to take advantage of this.

I would set the fields your are comparing to as indexes:

ALTER TABLE `table1` ADD INDEX(`number_complete`);
ALTER TABLE `table2` ADD INDEX(`number_cut`);

That should make the search run faster too.

String operations are expensive. If they are done on the scale of millions, then they get extremely expensive and you will wait for hours. The solution is to avoid string operations in your filters.

You will need to ask yourself a question: how is table1 and table2 related to each-other? Are they many-to-one or many-to-many? If they are many-to-many, you can create a table3(table1_id, table2_id) table. If they are many-to-one, then you can create a table2_id for the table1 table. These will be numeric fields and easy to filter and search by.

You will need to write a script which will populate the new column(s). Yes, you will wait for an hour, or even more, but only once. Afterwards searches will be quick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM