I have the following MySQL tables:
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', '[email protected]');
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);
If I run the following 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>';
}
My output is:
He has multiple skills! | He has multiple skills!
He has a great personality! | He has a great personality!
I would prefer to have it like this:
He has multiple skills! | He has a great personality!
I imagine I will have to wrangle my MySQL query but really not sure where to begin to achieve it this. I would really appreciate some guidance.
3
Answers
you are calling the two tables separately, you need to make an inner join between the two
exemple:
or
see this link
You can do it as follows :
Using
group_concat
to concat data from a groupDemo here
you should index your shared id in both tables and use foreign keys for better performance.
this approach is based on the Group concat function.
if you want 1 row for all results.
if you want 1 row per person.id