SQL“同时"将表数据读取到变量 [英] SQL 'while' to read a table data to a variable
问题描述
如何编写while
循环以将表中的数据填充到要在单独查询中使用的变量?
例如:select ITEM from Table1
How could I write a while
loop to populate data from a table to a variable to be used in a seperate query ?
EX: select ITEM from Table1
ITEM
A0001
B0001
C0003
D0005
E0032
如果我可以在列ITEM
至@var1
下获得所有结果,然后将其用于单独的查询中,例如:
If I can get all that results here under column ITEM
to @var1
and then use it in a seperate query like:
select *
from Table2
where @var1 = Item_table2 <-- a random column in table2
此查询应将@var1
从A0001
到E0032
匹配到Table2
中的Item_table2
列.
This query should match @var1
from A0001
to E0032
to the Item_table2
column in Table2
.
推荐答案
所以这是您的第一个表格:
So here is your first table:
mysql> select * from item_table1;
+-------+
| item |
+-------+
| A0001 |
| B0001 |
| C0003 |
| D0005 |
| E0032 |
+-------+
5 rows in set (0.01 sec)
现在,我们需要基于此表创建一个视图.视图是您在问题中通过@var1
调用的等效概念:
Now, we need to create a view based on this table. The view is the equivalent concept you call in your question by @var1
:
mysql> create view item_table2 as (select * from item_table1);
Query OK, 0 rows affected (0.30 sec)
让我们检查一下视图item_table2
(用您自己的话说是@var1
):
Let's check our view item_table2
(@var1
in your own words):
mysql> select * from item_table2;
+-------+
| item |
+-------+
| A0001 |
| B0001 |
| C0003 |
| D0005 |
| E0032 |
+-------+
5 rows in set (0.00 sec)
现在,您可以像这样在item_table1
中从item_table2
中选择任何项:
Now, you can select any item from item_table2
that exists in your item_table1
like this:
select it2.item from item_table2 it2 where it2.item='A0001'
这篇关于SQL“同时"将表数据读取到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!