2013-02-16 107 views
0

我有3個表格存儲了用戶註冊的常用數據:語言,國家,國籍。每個表格都有字段:ID名稱MySQL臨時表或視圖?

我得到了一個主表用戶它存儲幾乎所有來自用戶的數據。

另一臺名爲tableregistry它具有這樣的結構:

id | tableName | tableValue 

1 | finalJoin | 0 

2 | language | 1 

3 | country | 2 

4 |nationality| 3 

還有一,它存儲了一個名爲巧合公共數據共享許多用戶:

id | idUser | nTable | cValue 

因此,如果我們有第80名用戶在荷蘭居住,但他是來自祕魯的本地人,並且會說中文,數據會以這種方式保存下來(考慮到荷蘭擁有ID在國家表20,祕魯國籍有識別碼34在國籍表和中國語言對語言表中的id 22)

198 | 80 | 2  | 20 

199 | 80 | 3  | 34 

200 | 80 | 1  | 22 

所以,如果我們要進行搜索我使用存儲過程搜索巧合常見的數據只是獲得3個臨時表來獲取用戶1.來自某個國家2.在任何國家生活都不是原生的,3.說某種語言。

通過表用戶爲這些臨時表執行多重連接我們將獲得此搜索的用戶列表。

問題是。會更好地使用視圖還是隻保留臨時表策略?

回答

0

你有一個奇怪的模式。這個怎麼樣:

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 ; 

或者,如果你不關心denormalisation,你可能會下降countriesuser_rel_countries之間的區別

+0

好了,這是一個標準的模式,這是完全確定,但怎麼樣,如果我們的表現談論數千條記錄。而更糟糕的情況是......如果總體實體長大,那該怎麼辦?那麼,我必須爲每個新實體和各自的關係userid_entity?創建更多的表。 對不起,如果我聽起來有點討厭,但我試圖得到這個項目的最佳性能 – user1822528 2013-02-16 03:59:22

+0

如果他們是不同的類型,那麼是的 - 我會爲每個創建一個單獨的表。只要您在關鍵列上添加索引,這種性能就會很好地擴展。 – troelskn 2013-02-16 18:00:23

+0

您的意思是將索引放在user_rel_ *表的nationality_id,country_id和language_id列上? – user1822528 2013-02-17 21:24:47