【问题标题】:MySQL Temp Tables or View?MySQL 临时表或视图?
【发布时间】:2013-02-16 00:37:15
【问题描述】:

我有 3 个表存储了用户注册时的常用数据:语言、国家、国籍。每个表都有字段:idname

我有一个主表 users,它存储了几乎所有来自用户的数据。

另一个名为 tableregistry 的表具有以下结构:

id | tableName | tableValue

 1 | finalJoin | 0

 2 | language  | 1

 3 | country   | 2

 4 |nationality| 3

它存储的另一项称为 巧合 是共享许多用户的公共数据:

id | idUser | nTable | cValue

因此,如果我们有第 80 位用户住在荷兰,但他是秘鲁人并且说中文,则数据将以这种方式保存(考虑荷兰在 country 表中的 id 为 20,秘鲁人国籍在nationality表中的id为34,中文在language表中的id为22)

198 | 80    | 2      | 20

199 | 80    | 3      | 34

200 | 80    | 1      | 22

因此,如果我们要执行人员搜索,我会使用存储过程来搜索 巧合,只需获取 3 个临时表来获取用户 1.来自某个国家/地区 2.taht 的常见数据任何国家都不是本地人,并且 3.会说某种语言。

将这些临时表与表 users 进行多重连接,我们将获得此搜索的用户列表。

问题是。最好使用视图还是只保留临时表策略?

【问题讨论】:

    标签: mysql views temp-tables


    【解决方案1】:

    你有一个奇怪的架构。这个怎么样:

    CREATE TABLE users (
      id int(11) not null auto_increment,
      ...
    );
    
    CREATE TABLE languages (
      id int(11) not null auto_increment,
      name varchar(20) not null
    );
    
    CREATE TABLE countries (
      id int(11) not null auto_increment,
      name varchar(20) not null
    );
    
    CREATE TABLE nationalities (
      id int(11) not null auto_increment,
      name varchar(20) not null
    );
    
    CREATE TABLE user_rel_languages (
      user_id int(11) not null,
      language_id int(11) not null
    );
    
    CREATE TABLE user_rel_countries (
      user_id int(11) not null,
      country_id int(11) not null
    );
    
    CREATE TABLE user_rel_nationalities (
      user_id int(11) not null,
      nationality_id int(11) not null
    );
    

    因此,要获得具有特定语言 + 国家 + 国籍配置的用户,您可以从 users 中进行选择,并通过关系表加入这些表中的每一个。例如:

    select u.* from users u
    join user_rel_countries urc on urc.user_id = u.id 
    join user_rel_languages url on url.user_id = u.id 
    join user_rel_nationalities urn on urn.user_id = u.id 
    where country_id = 1 and language_id = 2 and nationality_id = 3 
    group by u.id ;
    

    或者,如果您不关心非规范化,您可以放弃 countriesuser_rel_countries 之间的区别

    【讨论】:

    • 好吧,这是一个标准模式,完全没问题,但如果我们谈论的是数千条记录,那么性能如何。更糟糕的情况……如果公共数据实体长大了怎么办。那么我是否必须为每个新实体和各自的关系 userid_entity 创建更多表?对不起,如果我听起来有点烦人,但我正在努力为这个项目获得最佳性能
    • 如果它们是不同的类型,那么是的 - 我会为每个创建一个单独的表。只要您在关键列上放置索引,其性能应该可以很好地扩展。
    • 您的意思是在 user_rel_* 表的 nationality_id、country_id 和 language_id 列上放置索引?
    • 两者。 rel 表的特殊之处在于它们具有组合的主键,并且这些列中的每一列都是外键。所以他们每个人都会定义 3 个索引。
    • 确定 rel 表上的复合主键以提供完整性。但是外键呢?我以为你正在开发 MyISAM
    猜你喜欢
    • 2011-07-26
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2011-11-03
    • 2011-01-20
    • 2011-06-22
    • 2021-05-18
    相关资源
    最近更新 更多