在查询中爆炸字段

时间:2010-11-02 10:55:13

标签: mysql

我在MySQL中有两个表。

CREATE TABLE IF NOT EXISTS `city` (
  `city_id` int(11) NOT NULL AUTO_INCREMENT,
  `city` varchar(50) NOT NULL,
  PRIMARY KEY (`city_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;


INSERT INTO `city` (`city_id`, `city`) VALUES
(1, 'London'),
(2, 'Moscow'),
(3, 'Perth'),
(4, 'tokyo'),
(5, 'seoul');


CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(20) NOT NULL,
  `cities_travel` varchar(50) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;


INSERT INTO `user` (`user_id`, `user_name`, `cities_travel`) VALUES
(1, 'todd', '5'),
(2, 'martin', '1,2,4');

我试图显示如下,

1 todd seoul
2 martin London,Moscow,Tokyo

如何构建查询以便我获得结果?

1 个答案:

答案 0 :(得分:1)

是的,更好的方法是使用feids创建一个单独的表“usercitytrans

id (auto increment)
user_id 
city_id

然后将数据保存在此事务表中。所以你可能有像

这样的数据
id  user_id  city_id
1   1        5
2   1        4
3   1        2
4   2        5
5   1        1

在这种情况下,您可以使用此sql

获取逗号分隔的城市
     select u.user_id, user_name, 
    group_concat(city_name separator  ', ' ) as usercities   from (user as u left join usercitytrans as ut
            on u.user_id = ut.user_id) left join city as c
            on ut.city_id = c.city_id
where user_id = 1
            group by ut.city_id