php - 如何创建一个包含由其他几个表组成的 post_id 和 post_table 列的表

标签 php mysql join

我有三个这样的表:

// Posts_1                  // Posts_2                  // Posts_3
+----+---------+            +----+---------+            +----+---------+
| id | content |            | id | content |            | id | content |
+----+---------+            +----+---------+            +----+---------+
| 1  | hello   |            | 1  | how are |            | 1  | you     |
+----+---------+            +----+---------+            +----+---------+

现在我需要创建一个名为 Posts_Index 的表,如下所示:

// Posts_index
+----+---------+------------+
| id | post_id | post_table |
+----+---------+------------+
| 1  | 1       | 1          |
| 2  | 1       | 2          |
| 3  | 1       | 3          |
+----+---------+------------+

我可以使用 php 来做到这一点(获取所有行,然后将它们插入到 Posts_index 表中),但是因为实际上这些表真的很大,所以使用 php 来做这件事需要很多时间。现在我想知道我是否可以只使用 MySQL 来做到这一点?

最佳答案

你的数据结构不好,应该把三个表合二为一。但是,您想要做的很简单:

create table Posts_Index (
    id int not null auto_increment primary key,
    post_id int,
    post_table int
);

insert into Posts_Index(post_id, post_table)
    select id, 1
    from posts_1;

insert into Posts_Index(post_id, post_table)
    select id, 2
    from posts_2;

insert into Posts_Index(post_id, post_table)
    select id, 3
    from posts_3;

为什么这是个坏主意?因为为了使用 Post_Index,您必须生成动态 SQL —— 或者相当复杂的 SQL 表达式。将这三个表合并到一个 Posts 表中会好得多,除非您有非常非常好的理由将它们分开。

此外,您无法在表之间指定正确的外键关系。

关于php - 如何创建一个包含由其他几个表组成的 post_id 和 post_table 列的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32679680/

相关文章:

mysql - 如何在 mysql 中进行 foreach 类型查询,将每一行与另一个表中的几行进行比较?

mysql - 当我进行 LEFT JOIN 时,我的 SIGNED INT 被转换为 UNSIGNED

php - Ajax、PHP、Javascript 在组合框选择后从数据库中提取值

php - MySQL 正在删除 html 表/Code Igniter 的最后一行

mysql - 选择多个表中 EACH 2 个表之间共有的所有值

php - 突然无法读取数据库?

php - 使用 php 从查询 mysql 创建姓名和电子邮件

mysql - 加入两个查询表

php - utf8、php 和 mysql 的问题

php - 在自定义构建的 php7 上启用 Curl