MySQL存储过程可循环访问2个表,选择值并存储在第3个表中

时间:2018-11-23 06:21:53

标签: mysql stored-procedures

我有3个表usersmemosmemos_read

users

+---+----------+
|ID | NAME     |
+---+----------+
| 1 | Mike     |
| 4 | Susan    |
| 5 | Peter    |
| 6 | Mary     |
+---+----------+

memos

+---+----------+
|ID | CONTENT  |
+---+----------+
| 15| Hello    |
| 16| World    |
| 17| Foo      |
| 23| Bar      |
+---+----------+

我想创建一个带有嵌套循环的存储过程,以为已读取的备忘录创建一个“读取地图”,创建类似以下内容的

memos_read

+---------+----------+
| MEMO_ID | USER_ID  |
+---------+----------+
|    15   |    1     |
|    15   |    4     |
|    15   |    5     |
|    15   |    6     |
|    16   |    1     |
|    16   |    4     |
|    16   |    5     |
|    16   |    6     |
|    17   |    1     |
|    17   |    4     |
|    17   |    5     |
|    17   |    6     |
|    23   |    1     |
|    23   |    4     |
|    23   |    5     |
|    23   |    6     |
+---------+----------+

这可能吗?谢谢你!

2 个答案:

答案 0 :(得分:1)

您可以使用CREATE TABLE ... SELECT语法来创建 <div class="form-group"> <label class="col-md-3 control-label">FAQ Type :-</label> <div class="col-md-6"> <select name="faq_type" id="faq_type" class="select2" required> <option value="0" <?php if($row['your_db_field'] == "0") { ?> selected="selected" <?php } ?> >Text</option> <option value="1" <?php if($row['your_db_field'] == "1") { ?> selected="selected" <?php } ?> >Image</option> <option value="2" <<?php if($row['your_db_field'] == "3") { ?> selected="selected" <?php } ?> >Video</option> </select> </div> </div> 表:

memos_read

输出根据您的要求。 Demo on dbfiddle

答案 1 :(得分:1)

@Nick的answer应该为您工作;但是,如果您对创建新表不感兴趣,而是在查询中动态使用“读取映射”;您可以使用Derived Table

一般查询结构如下:

SELECT
  read_map.MEMO_ID,
  read_map.USER_ID,
  ...
FROM 
(
  SELECT 
    m.ID AS MEMO_ID, 
    u.ID AS USER_ID
  FROM users AS u 
  CROSS JOIN memos AS m 
) AS read_map 

...  -- here you can join with other tables as required
WHERE ...