How to write a mysql query correctly?

  • 0
    I have a table, I make a query to it and get a result like this:
    {
        id:1,
        name:'vasya',
        age:20
    },
    {
        id:2,
        name:'petya',
        age:22
    },
    {
        id:3,
        name:'zina',
        age:18
    }

    I have a second table that lists the hobby in userid - hobby format. I need to get the result like this:
    {
        id:1,
        name:'vasya',
        age:20,
        hobby: 'none'
    },
    {
        id:2,
        name:'petya',
        age:22б
        hobby:'box'
    },
    {
        id:3,
        name:'zina',
        age:18,
        hobby:'tennis'
    }


    How do I link results from two tables?
    MySQL Anonymous, Jun 21, 2019

  • 2 Answers
  • 0
    SELECT u.id, u.name, u.age, h.hobby
    FROM users u
    LEFT JOIN hobbies h
    ON u.id = h.user_id;



    Explanation in "human language":


    - select id, name, age from table u (alias users), and also hobby from table h (alias hobbies)

    - from the users table (which will be accessed by the alias u)

    - and combine with the results from the hobbies table (which we will refer to by the alias h)

    - and the union itself is done according to the rule where the id from the u (users) table is equal to the user_id from the h (hobbies) table


    LEFT JOIN takes as a basis the table on the left (hence LEFT), that is, the one that is first in the SELECT FROM itself. Then he adds the new temporary table with columns and values ​​obtained from the second table (specified in the LEFT JOIN).


    The output is:

    Anonymous

  • 0
    Use Left Join
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!