0

我的数据库中有产品表,如下所示:

shop1_products
shop2_products
shop3_products
.....
....
...
shop100_products

我想展示现场尝试过的所有表的产品,union但我认为 100 个表不行。

我知道,如果我们通过制作一个包含 shopid 列的产品表来做到这一点,它会变得简单。但是在我的网站逻辑中我不能这样做,因为这种结构会迫使我在其他模块上做双重工作。

我正在考虑使用存储过程来做到这一点,但对于stored procedure.

您怎么看,我们如何以有效的方式做到这一点?

如果stored procedure最好这样做,请向我提供示例代码或参考链接

4

1 回答 1

1
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;
于 2012-08-31T10:47:49.260 回答