连接MySQL结果(是否连接?)[重复]

kxxlusnw  于 2023-02-03  发布在  Mysql
关注(0)|答案(3)|浏览(104)
    • 此问题在此处已有答案**:

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查询,但真的不知道从哪里开始实现它这一点。我真的很感激一些指导。

5f0d552i

5f0d552i1#

您可以按以下步骤操作:

SELECT p.id, group_concat(r.review_body)
FROM person p
inner join review r on r.person_id = p.id
group by p.id

使用group_concat连接组中的数据
Demo here

a64a0gku

a64a0gku2#

您正在分别调用这两个表,需要在这两个表之间建立内连接
例:

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;


see this link

0ve6wy6x

0ve6wy6x3#

你应该在两个表中索引你的共享ID,并使用外键来获得更好的性能。2这个方法是基于Groupconcat函数的。

SELECT 1,GROUP_CONCAT( review_body SEPARATOR ' | ') as goruped_result 
FROM person
INNER JOIN review
ON review.person_id = person.id;

相关问题