简体   繁体   中英

How to use “LIKE” function on “FROM” clause in MySQL

I am trying to query a specific table based on a user input, and want to query the table that contains that user input as the search_id in the name. For example, the table names are structured as run_000000_search_000000_lda_000000 and I want to get the table that has the same search_id as the on they put in.

I know when "LIKE" is used on the Where clause you can get a column with a specific string or int in the name. However, I have found nothing on using it with the "FROM" clause.

Specific hardcoded query for search_id 50

SELECT *
FROM `run_000044_search_000050_lda_000366`;

In summary, how can I get the table that has the same search_id as the one the user put in. Also trying to use the run and lda to form a full table name does not work because there is no noticeable pattern in between the 3 names.

I also can use dynamic sql but am not sure how to do it.

After searching online I have finally found out a solution. The infomation_schema.tables contains a column will a table names. From here you can query the full name of the table and use that in another query. I think that a full example makes it much easier to understand:

SELECT * FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE '%_search_000050_lda_%';

SELECT * FROM INFROMATION_SCHEMA.TABLES

^ selects table will containing all table names and

WHERE TABLE_NAME LIKE '%_search_000050_lda_%';

^ search all tables for whats in the quotes. Replace the '%_seach_000050_lda_%' with the Like statement you need for the table

LIKE is usually used in WHERE clause after FROM for example

SELECT * FROM table_name WHERE field LIKE 'value';

you can also compare number or int field by '=' operator which return a specific record.

SELECT * FROM table_name WHERE id = 30;

if you want extract details from specific record set of another table you can subquery method for example refer this link

you can also use dynamic sql query.refer this link for dynamic sql query

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