Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL + PHP: Select all results from one table for each result of another

Tags:

sql

php

mysql

I have the following two tables in my database:

TABLE 1: Specials
---------------------------------------------
| Special ID | Special Name | Special Image |
 --------------------------------------------
|     1      |   Special 1  |     1.jpg     |   
|     2      |   Special 2  |     2.jpg     |
|     3      |   Special 3  |     3.jpg     |
---------------------------------------------

TABLE 2: Special Items
---------------------------
| Item ID | Item Name     |
---------------------------
|     1      |   Service  | 
|     2      |    Clean   |
|     3      |     Dry    |
---------------------------

When pulled from the database I am looking for a way to achieve this (Column 4 will be a drop down list):

EDIT SPECIALS (Columns 1-3: Table 1) (Column 4: All results from Table 2)
-------------------------------------------------------------------
| Special ID | Special Name | Special Image | Items               |
-------------------------------------------------------------------
|     1      |   Special 1  |     1.jpg     | Service, Clean, Dry |      
|     2      |   Special 2  |     2.jpg     | Service, Clean, Dry | 
|     3      |   Special 3  |     3.jpg     | Service, Clean, Dry |
-------------------------------------------------------------------    
like image 841
advermark Avatar asked Nov 26 '25 16:11

advermark


2 Answers

Make use of MySQL GROUP_CONCAT() method which is able to concatenate rows.

SELECT  a.*,
        (SELECT GROUP_CONCAT(ItemName) FROM SpecialItems) ItemList
FROM    Specials a
  • SQLFiddle Demo
  • GROUP_CONCAT()

OUTPUT

╔════════════╦══════════════╦═══════════════╦═══════════════════╗
║ SPECIAL ID ║ SPECIAL NAME ║ SPECIAL IMAGE ║     ITEMLIST      ║
╠════════════╬══════════════╬═══════════════╬═══════════════════╣
║          1 ║ Special 1    ║ 1.jpg         ║ Service,Clean,Dry ║
║          2 ║ Special 2    ║ 2.jpg         ║ Service,Clean,Dry ║
║          3 ║ Special 3    ║ 3.jpg         ║ Service,Clean,Dry ║
╚════════════╩══════════════╩═══════════════╩═══════════════════╝
like image 128
John Woo Avatar answered Nov 28 '25 06:11

John Woo


Use GROUP_CONCATE MySQL that will help you to combine result with comma separations.

Example

like image 40
Dipesh Parmar Avatar answered Nov 28 '25 06:11

Dipesh Parmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!