简体   繁体   中英

MySQL Temp Tables or View?

I got 3 tables that have stored common data from registration from users: languages, countries, nationalities . Each table have fields: id and name .

I got a main table users where it stores almost all the data from the users.

Another table called tableregistry which it has this structure:

id | tableName | tableValue

 1 | finalJoin | 0

 2 | language  | 1

 3 | country   | 2

 4 |nationality| 3

And one more that it stores called coincidences the common data that share many of the users:

id | idUser | nTable | cValue

So if we have the 80th user taht live in Netherlands but he's native from Peru and speak Chinesse the data would save in this way (considering Netherlands have the id 20 in the country table, the peruvian nationality have id 34 in the nationality table and the chinese language have the id 22 on the language table)

198 | 80    | 2      | 20

199 | 80    | 3      | 34

200 | 80    | 1      | 22

So if we want to perform a search of persons i use a stored procedure to search on coincidences the common data just getting 3 temporary tables to get users 1.from certain country 2.taht live on any country than not be the native and 3.speak a certain language.

Doing a multiple join for these temporary tables with the table users we would get a list of users for this search.

The question is. Would be better use a view or just keep the temporary table strategy?

You have a weird schema. How about this:

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
);

So to get a user with a specific configuration of language + country + nationality, you would would select from users and join with each of those tables through the relation-table. Eg:

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 ;

Or if you don't care about the denormalisation, you could drop the distinction between countries and user_rel_countries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM