M
M
Mikhail Abroskin2018-02-20 09:01:39
MySQL
Mikhail Abroskin, 2018-02-20 09:01:39

How to build a query in MySQL?

Good day, friends and comrades!
Can you please tell me how to make such a request purely in SQL, as well as in Laravel in the controller?
The task is this, there are two
tables 1 table - Users, in it, for example, columns - id, name, age (age), ref_id (user id in the same table, which is above this user), group_id (which group the user belongs to)
2-table - Groups, it has columns - id, name
Well, in fact, you need to make such a request to select users whose age is greater than the user specified in their ref_id, while selecting the fields - name, age, and also specify the name of the group to which belongs to this user.
table examples:
1 table:

  1. Petrov | 22 | 0 | one
  2. Ivanov | 23 | 1 | one
  3. Sidorov | 20 | 1 | 2
  4. Makeev | 24 | 2 | one

2 table:
  1. Group 1
  2. Group 2

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2018-02-20
@miker059

"SELECT u1.name, u1.age, g.name as group FROM users as u1 
LEFT JOIN users as u2 
ON u1.ref_id = u2.id 
LEFT JOIN group as g 
ON u1.group_id = g.id 
WHERE u1.age > u2.age"

If everything is fine with the indexes, it will work pretty fast.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question