1

如何在 mysql 中将 2 个表加入 1 个表?

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `p`
-- ----------------------------
DROP TABLE IF EXISTS `p`;
CREATE TABLE `p` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of p
-- ----------------------------
INSERT INTO `p` VALUES ('1', 'jimmy');
INSERT INTO `p` VALUES ('2', 'tina');


SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `t`
-- ----------------------------
DROP TABLE IF EXISTS `t`;
CREATE TABLE `t` (
  `id` int(11) NOT NULL,
  `tag` varchar(255) NOT NULL default '',
  `value` varchar(255) default NULL,
  PRIMARY KEY  (`id`,`tag`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t
-- ----------------------------
INSERT INTO `t` VALUES ('1', 'name', '111');
INSERT INTO `t` VALUES ('1', 'age', '30');
INSERT INTO `t` VALUES ('2', 'bag', 'miki');
INSERT INTO `t` VALUES ('2', 'boy friend', 'jimmy');

图片显示了我想要得到的东西。在此处输入图像描述

4

1 回答 1

4
SELECT  p.id, p.name,
        GROUP_CONCAT(CONCAT(tag, ':', value)) tags
FROM    p
        INNER JOIN t
            ON p.iD = t.id
GROUP   BY p.id, p.name

输出

╔════╦═══════╦═══════════════════════════╗
║ ID ║ NAME  ║           TAGS            ║
╠════╬═══════╬═══════════════════════════╣
║  1 ║ jimmy ║ age:30,name:111           ║
║  2 ║ tina  ║ bag:miki,boy friend:jimmy ║
╚════╩═══════╩═══════════════════════════╝
于 2013-03-21T09:25:32.940 回答