[英]A simple way to normalize a table
I have a table like this -this is a part of users table which is getting update with more rows when a user is registering : 我有一个这样的表-这是用户表的一部分,当用户注册时,该表将更新更多行:
user_id languages
1 english, french
2 english,german,french
3 german
4 english, spanish
and in order to do a littel search I'm intrested of transforming this table into: 为了进行小字搜索,我很想将这张桌子变成:
user_id language
1 english
1 french
2 english
2 german
2 french
3 german
4 english
4 spanish
Comment : not creating a new table but just right the correct select query from users table to do that. 注释:不创建新表,而只是从用户表中执行正确的选择查询即可。 I'm using mysql with phpmyadmin.
我正在将mysql与phpmyadmin一起使用。 Any help will be welcome.
任何帮助都将受到欢迎。 Thank's.
谢谢。
As others have stated, storing comma-separated values in a column will cause you all sorts of pain over time. 正如其他人所述,将逗号分隔的值存储在列中会随着时间的流逝而引起各种麻烦。 Having said that...
话说回来...
Create a numbers table (one way to do that is described here ). 创建一个数字表( 此处描述了一种方法)。 Once you have that, you can use it to split your comma-separated values onto separate rows:
一旦有了它,就可以使用它来将逗号分隔的值拆分为单独的行:
select lang.user_id,
SUBSTRING_INDEX(SUBSTRING_INDEX(lang.languages, ', ', numbers.n), ', ', -1) language
from numbers
inner join lang on CHAR_LENGTH(lang.languages) - CHAR_LENGTH(REPLACE(lang.languages, ', ', ' ')) >= numbers.n - 1
order by lang.user_id, numbers.n;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.