Mysql select from multiple tables

What you do here is called a JOIN (although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.

But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!

If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).

In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):

SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id
name     price   photo
fanta    5       ./images/fanta-1.jpg
dew      4       ./images/dew-1.jpg

In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:

SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id
name     price   photo
fanta    5       ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew      4       ./images/dew-1.jpg,./images/dew-2.jpg

However, this can get dangerous if you have , within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.

  1. HowTo
  2. MySQL Howtos
  3. SELECT From Multiple Tables in MySQL

Created: October-29, 2020 | Updated: December-10, 2020

  1. Use GROUP BY food to SELECT From Multiple Tables
  2. Use JOIN to SELECT From Multiple Tables in MySQL
  3. Use GROUP_CONCAT() and Manipulate the Results in MySQL

This tutorial shows you how to query SELECT from multiple tables in a single script with the use of MySQL.

Let’s demonstrate one scenario:

SELECT name, price, details, type,  FROM food, food_order  WHERE breakfast.id = 'breakfast_id'

Now let’s imagine sample tables for each FROM entry:

  • food
food_idnamepriceoptions
1 Eggs 10.00 Scrambled, Sunny Side, Boiled
2 Ice cream 30.00 Vanilla, Strawberry, Chocolate
3 Ramen 12.00 Regular, Spicy
  • food_menu
order_idphotofood_id
1 eggs_scrambled.jpg 1
2 eggs_sunnyside.jpg 1
3 eggs_boiled.png 1
4 icecream_vanilla.jpg 2
5 icecream_strawberry.jpg 2
6 ice_cream_chocolate.jpg 2
7 ramen_regular.jpg 3
8 ramen_spicy.jpg 3

Basing on the tables above, we can see that Eggs have 3 photos, Ice cream also has 3, while Ramen has 2. The output we want to produce is an aggregated table of food and food_menu, display all the food together and combining them with the corresponding photos in the menu.

If we query this:

SELECT name, price, options, photo 
FROM food, food_menu 
WHERE food_id = '1'

The result would be this:

namepriceoptionsphoto
1 Eggs Scrambled, Sunny Side, Boiled eggs_sunnyside.jpg
2 Eggs Scrambled, Sunny Side, Boiled eggs_scrambled.jpg
3 Eggs Scrambled, Sunny Side, Boiled eggs_boiled.jpg

The data is duplicated because there are multiple rows of food_menu related to food. In this case, there are 3 photos in food_menu that are tied directly to Eggs.

It is not possible for a simple query to join all the entries in food_menu in one single row, since they are all considered as separate entities that are related to table food.

If you want to query food and food_menu at the same time in a single row, then here are a few options to do that.

Use GROUP BY food to SELECT From Multiple Tables

This approach uses GROUP BY to aggregate both tables in one result. The drawback, however, is you will only get the first instance of food_menu since we’re forcing the results to be unique.

Below is the query to GROUP BY food table:

SELECT name, price, options, photo
FROM food, food_menu
WHERE food_id = '1' 
GROUP BY food_id

It would then display the following result:

namepriceoptionsphoto
1 Eggs Scrambled, Sunny Side, Boiled eggs_sunnyside.jpg

We now have satisfied the condition, although only one photo is returned, which is the first instance of food_menu found by the query.

Use JOIN to SELECT From Multiple Tables in MySQL

This approach makes use of SQL’s JOIN or RIGHT JOIN command.

Instead of having 2 FROM conditions in the script, we JOIN food_menu based on its food_id foreign key. We aliased f for food and fm for food_menu

SELECT f.name, f.price, f.options, fm.food_menu
FROM food AS f
JOIN food_menu AS fm ON fm.food_id = f.food_id
WHERE food_id = '1'
GROUP BY f.food_id

Although this method is different from the previous one, it produces the same result. It returns the first instance of food_menu because GROUP BY forces the query to return unique rows based on its condition.

namepriceoptionsphoto
1 Eggs Scrambled, Sunny Side, Boiled eggs_sunnyside.jpg

Use GROUP_CONCAT() and Manipulate the Results in MySQL

A workaround for the problem of the previous solution is to use GROUP_CONCAT() to put all the results of food_menu in one single string, therefore it will be possible to put all their records in a single row.

What Is GROUP_CONCAT()?

GROUP_CONCAT is a function that combines the data from multiple rows to a single field. It’s a GROUP BY special function that returns a modified string if the group contains at least 1 non-null value. Otherwise, it returns NULL.

We modify the query above to GROUP_CONCAT() photos column to concatenate the results into one string.

SELECT name, price, options, GROUP_CONCAT(photo, ', ')
FROM food, food_menu
WHERE food_id = '1' 
GROUP BY food_id

By doing this, we concatenate the photo column of food_menu so that only one row per unique entry of food will be generated. The result would be as displayed:

namepriceoptionsphoto
1 Eggs Scrambled, Sunny Side, Boiled eggs_sunnyside.jpg,eggs_scrambled.jpg,eggs_boiled.jpg

As you can see, it concatenated the 3 photo columns that are related to Eggs in the food table.

If we remove the GROUP BY and WHERE condition.

SELECT name, price, options, GROUP_CONCAT(photo, ', ')
FROM food, food_menu

The result would look like this

namepriceoptionsphoto
1 Eggs Scrambled, Sunny Side, Boiled eggs_sunnyside.jpg,eggs_scrambled.jpg,eggs_boiled.jpg
2 Ice Cream Vanilla, Strawberry, Chocolate icecream_vanilla.jpg,icecream_strawberry.jpg,icecream_chocolate.jpg
3 Ramen Regular, Spicy ramen_regular.jpg,ramen_spicy.jpg

Do be careful using GROUP_CONCAT(), if your string contains a comma and your CONCAT delimiter is a comma as well, parsing your column would corrupt your data.

So before you use this function, make sure that your delimiter is an invalid character for the column that you’re manipulating it with.

Related Article - MySQL Table

  • Create Table Alias With MySQL VIEW and MERGE
  • Drop Constraint From the MySQL Table
  • Update Multiple Tables With One Query in MySQL
  • Optimize Tables and Databases in MySQL
  • Mysql select from multiple tables

    Can we SELECT from multiple tables in MySQL?

    You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table. You can use JOINS in the SELECT, UPDATE and DELETE statements to join the MySQL tables. We will see an example of the LEFT JOIN also which is different from the simple MySQL JOIN.

    How do you SELECT multiple tables?

    Example syntax to select from multiple tables:.
    SELECT p. p_id, p. cus_id, p. p_name, c1. name1, c2. name2..
    FROM product AS p..
    LEFT JOIN customer1 AS c1..
    ON p. cus_id=c1. cus_id..
    LEFT JOIN customer2 AS c2..
    ON p. cus_id = c2. cus_id..

    Can you SELECT from 2 tables in SQL?

    In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.

    How do I SELECT multiple values from one table in MySQL?

    Learn MySQL from scratch for Data Science and Analytics To select multiple values, you can use where clause with OR and IN operator.