[英]Mysql fetch data from similar but not related tables
我的數據庫中有產品表,如下所示:
shop1_products
shop2_products
shop3_products
.....
....
...
shop100_products
我想顯示站點上所有表的產品,並嘗試使用union
但我認為100表不能正常運行。
我知道,如果我們通過在一個帶shopid列的產品表中進行操作,將使其變得簡單。 但是在我的網站邏輯中,我無法做到這一點,因為這種結構會迫使我在其他模塊上做雙重工作。
我正在考慮使用存儲過程來做到這一點,但是對於stored procedure
卻是新的。
您如何看待,我們如何才能有效地做到這一點?
如果最好使用stored procedure
來執行此操作,請提供示例代碼或參考鏈接
do like this put all the table names in a temp table then follow these steps in while loop.
Then create a table results with all the required columns
for each @tablename
insert into results
select product name ,id,category... from @tablename
repeat
Then finally select distinct * from results
- - - - - - - - - - - - - - - - -碼 - - - - - - - - -------------------------------------
create table temp(id int auto_increment primary key,tblname varchar(100));
insert into temp(tblname)
VALUES('shop1_products'),('shop2_products'),('shop3_products')...('shop100_products');
select min(id),max(id) into @vmin,@vmax from temp;
select @vmin,@vmax;
create table results(productname varchar(100),id int,category varchar(100)...);
while(@vmin <= @vmax)
Do
select tblname into @tablename from temp;
INSERT INTO results(product name ,id,category...)
select product name ,id,category... from @tablename
SET @vmin=@vmin+1;
END WHILE;
select distinct * from results;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.