I’m having trouble on joining three tables.
First attempt on joining two tables is success, but on third table the results are not correct…
I have three tables machine_list is mainTable then applicable_rpm and applicable_product are some details of machine_list
Table: machine_list
| id | machine_number | machine_brand |
---------------------------------------
| 1 | MN-1 | TOYO |
| 2 | MN-2 | AMITA |
Table: applicable_rpm
| id | mc_recordID | rpm |
--------------------------
| 1 | 1 | 20 |
| 2 | 2 | 20 |
| 3 | 2 | 25 |
Table: applicable_product
| id | mc_recordID | productline|
---------------------------------
| 1 | 1 | mono |
| 2 | 2 | mono |
| 3 | 2 | poly |
I want to return like this:
| machine_number | rpm | twine |
----------------------------------------
| MN-1 | 20 | mono |
| MN-2 | 20, 25 | mono, poly |
I first try joining the two table with this query:
SELECT t1.machine_number, GROUP_CONCAT(' ', t2.speed) machine_speed
FROM machine_list t1
INNER JOIN applicable_rpm t2 ON t1.id = t2.mc_recordID
GROUP BY t1.id;
and the result are:
| machine_number | rpm |
---------------------------
| MN-1 | 20 |
| MN-2 | 20, 25 |
which is correct, but when i try on third table it duplicates it’s value.
this my query:
SELECT t1.machine_id,
GROUP_CONCAT(' ', t2.speed) machine_speed,
GROUP_CONCAT(' ', t3.twine) production_line
FROM machine_list t1
INNER JOIN applicable_rpm t2 ON t1.id = t2.mc_recordID
INNER JOIN applicable_product t3 ON t1.id = t3.mc_recordID
GROUP BY t1.id;
and the result are:
| machine_number | rpm | twine |
----------------------------------------
| MN-1 | 20, 20 | mono, poly |
| MN-2 | 20, 25 | mono, poly |
What should i do?
2
Answers
If you don’t group, you’ll see there are two rows associated with MN-2. So if you group_concat it’ll display the value for the selected column from both rows.
You’re going to need to use nested selects here. Something like the following:
As an after thought you could also try GROUP_CONCAT with DISTINCT
Looks like your join is producing duplicate rows.
We can achieve the desired output by making use of subqueries.
This will return you the expected output :