- 此问题在此处已有答案**:
Can I concatenate multiple MySQL rows into one field?(16个答案)
How to use GROUP BY to concatenate strings in MySQL?(6个答案)
3小时前关门了。
我有以下MySQL表:
CREATE TABLE `person` (
`id` int NOT NULL AUTO_INCREMENT,
`reference` varchar(100) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
INSERT INTO `person` (`id`, `reference`, `email`) VALUES
(1, 'PK001', 'paulk@gmail.com');
CREATE TABLE `review` (
`id` int NOT NULL AUTO_INCREMENT,
`review_type` varchar(255) NOT NULL,
`review_body` varchar(255) NOT NULL,
`person_id` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
INSERT INTO `review` (`id`, `review_type`, `review_body`, `person_id`) VALUES
(1, 'Personality', 'He has a great personality!', 1),
(2, 'Skills', 'He has multiple skills!', 1);
如果我运行下面的PHP:
$sql = "SELECT * FROM person, review WHERE person.id = review.person_id;";
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
echo $row['review_body'];
echo ' | ';
echo $row['review_body'];
echo '<br>';
}
我的输出是:
He has multiple skills! | He has multiple skills!
He has a great personality! | He has a great personality!
我更喜欢这样:
He has multiple skills! | He has a great personality!
我 * 想象 * 我将不得不争吵我的MySQL查询,但真的不知道从哪里开始实现它这一点。我真的很感激一些指导。
3条答案
按热度按时间5f0d552i1#
您可以按以下步骤操作:
使用
group_concat
连接组中的数据Demo here
a64a0gku2#
您正在分别调用这两个表,需要在这两个表之间建立内连接
例:
或
see this link
0ve6wy6x3#
你应该在两个表中索引你的共享ID,并使用外键来获得更好的性能。2这个方法是基于Groupconcat函数的。