我有一个关于如何使用id和项目名称
在数据库中与2个表进行联系的问题我有两个数据库,一个是:
CREATE TABLE `alchimie` (
`id` smallint(5) unsigned NOT NULL auto_increment,
`id_potiune` tinyint(3) unsigned NOT NULL default '0',
`nume_potiune` varchar(40) NOT NULL default '',
`nivel_potiune` tinyint(3) unsigned NOT NULL default '1',
`nivel_caracter` tinyint(2) unsigned NOT NULL default '1',
`obiecte_necesare` tinytext NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
这是插入数据的表
Image 1 http://img705.imageshack.us/img705/4522/55040113.png
第二个数据库的一部分是
CREATE TABLE `iteme` (
`obiect` int(11) NOT NULL auto_increment,
`nume` text collate utf8_polish_ci NOT NULL,
------------------------------------------------
PRIMARY KEY (`obiect`),
KEY `tip` (`tip`,`pret_cumparare`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8
(obiect in my case is id )
我不知道如何从php id调用与第二个数据库中的名称(nume)相关联
而不是0,0,0,0,0(在db中写入)由','分隔 我想说出项目的名称
示例:
INSERT INTO `iteme` VALUES ('1', 'Name of item 1', .....');
INSERT INTO `iteme` VALUES ('2', 'Name of item 2', .......');
INSERT INTO `iteme` VALUES ('3', 'Name of item 3 ', .......');
和
INSERT INTO `alchimie` VALUES ('1', '100', 'Fusar ', '1', '1', '1, 2, 3');
它将会出现在“obiecte necesare”
Image 2 http://img59.imageshack.us/img59/1614/78551339.png
我希望这次我终于可以让你明白我想做什么却失败了
答案 0 :(得分:0)
首先,您需要iteme
表格中的一列,以便在以下示例中引用alchimie
,我为其命名为alchimie_id
。
现在LEFT JOIN
,GROUP BY
和GROUP_CONCAT()
将通过查询完成这项工作
SELECT a.nume_potiune,
a.nivel_potiune,
a.nivel_caracter,
i.obiecte_necesare
FROM alchimie a LEFT JOIN
(
SELECT alchimie_id,
GROUP_CONCAT(nume) obiecte_necesare
FROM iteme
GROUP BY alchimie_id
) i
ON a.id = i.alchimie_id
示例输出:
| NUME_POTIUNE | NIVEL_POTIUNE | NIVEL_CARACTER | OBIECTE_NECESARE | ---------------------------------------------------------------------------------------------- | Fusar | 1 | 1 | Name of item1,Name of item2,Name of item3 | | Caracuda | 1 | 1 | (null) | | Tipar Chiscar | 2 | 1 | (null) | | Salau | 2 | 2 | (null) |
这是 SQLFiddle 演示。