MySql,连接表WHERE IN()

时间:2016-07-13 23:23:29

标签: mysql join where

我这里有两个表格和结构:

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `membership` varchar(12) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


CREATE TABLE `memberships` (
  `id` int(1) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(30) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;



INSERT INTO `memberships` (`id`, `title`) VALUES
(1,  'Basic'),
(2,  'Bronze'),
(3,  'Gold'),
(4,  'Platinum');

INSERT INTO `users` (`id`, `username`, `membership`) VALUES
(1,  'john', '0'),
(2,  'mike', '1,2'),
(3,  'peter', '3,4'),
(4,  'jane', '3'),
(5,  'rick', '1,2,3');

我需要加入这两个表,并使用IN函数列出所有用户的会员资格。

这是我尝试过的,但我无法以这种方式加入表格:

SELECT 
  *.u
  m.title AS title 
FROM
  `users` AS u 
  LEFT JOIN `memberships` AS m 
    WHERE m.id IN(u.membership)
ORDER BY u.username; 

我想拥有的是这样的:

username              membership
=====================================
john                  null
mike                  Basic, Bronze
peter                 Gold, Platinum
jane                  Gold
rick                  Basic, Bronze, Gold

我也创建了SQL小提琴:http://sqlfiddle.com/#!9/39b6e1

1 个答案:

答案 0 :(得分:0)

这个怎么样?

SELECT 
  u.*,
  GROUP_CONCAT(m.title SEPARATOR ', ') as memberships
FROM
  `users` AS u 
  LEFT JOIN `memberships` AS m 
    ON FIND_IN_SET(m.id, u.membership)
GROUP BY u.username
ORDER BY u.username 

给你:

id  username    membership  memberships
4   jane        3           Gold
1   john        0           (null)
2   mike        1,2         Bronze, Basic
3   peter       3,4         Gold, Platinum
5   rick        1,2,3       Basic, Bronze, Gold

Updated SQL Fiddle