简体   繁体   中英

Search in multiple table based on column numbers

table1 has 6 column

table2 has 8 column

table3 has 10 column

table4 has 12 column

all the tables have a common NAME, say pid. i want to make a query in PHP which says, if, pid is found in table1, send the data to PHP query or else search in table2, or if not found, search in table3 or next in table4.

is there any way i can differentiate before hand based on column numbers, which table to search before making the query in PHP.

Since you did not attached code , logical solution is mentioned here. You could do proceed by checking if column exist then search in that

At very first , you will have to get all table names in array as

SHOW TABLES FROM db_name 

Now go for a foreach loop and break if count >0

 SELECT count(*) as c,TABLE_NAME as tn
    FROM information_schema.COLUMNS 
    WHERE 
        TABLE_SCHEMA = 'db_name' // your db name
    AND TABLE_NAME = 'table_name' // from loop get it
    AND COLUMN_NAME = 'pid' // column name

Now check c in php if >0 return tn and then break

Finally do your search query in table what you get from tn

If you have query on integer value. Then You can maintain a Range table for that. It stores only table name like table1 and its minimum key value and maximum key value . If any query on that integer value then we can found the table name from which this record belong by using range table and get it from target table like table1. Range table is small, its have 5-6 records as you said so very less time taking. Now go to your destination table and find data.

Caution: This methods have its own pros & cons. I am just sharing my views

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