Home > Software engineering >  Select from multiple tables on reference table with same column name MYSQL/PHP
Select from multiple tables on reference table with same column name MYSQL/PHP

Time:11-16

I need some help with MySQL/PHP. Which is the faster execution in code point of view.

I have below tables

1. table_content
--------------------------------
id      | section   | content_id
--------------------------------
1       | A         | 15
2       | B         | 25
3       | A         | 9
--------------------------------


2. table_a
--------------------------------
id      | name      | message
--------------------------------
9       | John      | Hello Everyone
15      | Smita     | Hi
17      | Vinayak   | How are you?
--------------------------------


3. table_b
--------------------------------
id      | label     | description
--------------------------------
1       | David     | D1
5       | Alia      | D2
25      | Vinay     | D3
--------------------------------

I have above table structure. For me table_content is main table. I want below output through MySQL/PHP [As array and section as key].

Output
------------------------------------------------
id      | section   | name      | message
------------------------------------------------
1       | A         | Smita     | Hi
2       | B         | Vinay     | D3
3       | A         | John      | Hello Everyone
------------------------------------------------

I have tried with SWITCH case. But not getting exact output.

Which is the better performance and fast execution? with MySQL or PHP. I have thousands of data like this.

Please help me to solve this problem.

CodePudding user response:

Should be acheved via a JOIN.

Also ensure you have configured appropriater indexing, otherwise it will perform badly when you get to a large volume of data.

CodePudding user response:

As i posted in my comment you need to Join the both tables, which must be UNION

SELECT tc.`id`, tc. `section` ,t1.`message`
FROM table_content tc JOIN (SELECT `id`, `name`, `message` FROM table_a UNION SELECT `id`, `label`, `description` FROM table_b) t1 
ON tc.`content_id` = t1.`id`
id | section | message       
-: | :------ | :-------------
 1 | A       | Hi            
 2 | B       | D3            
 3 | A       | Hello Everyone

db<>fiddle here

  • Related