T
T
t38c3j2016-02-17 02:58:39
PHP
t38c3j, 2016-02-17 02:58:39

How to make a selection from 3 tables?

There are three tables with the following content:

mysql> select * from `users`;
+----+-------+----------+----------+
| id | email | password | nickname |
+----+-------+----------+----------+
|  1 | email | password | nickname |
+----+-------+----------+----------+
|  2 | email | password | nickname |
+----+-------+----------+----------+

mysql> select * from `users_data`;
+---------+-----------+----------+
| user_id | firstname | lastname |
+---------+-----------+----------+
|       1 | firstname | lastname |
+---------+-----------+----------+
|       2 | firstname | lastname |
+---------+-----------+----------+

mysql> select * from `users_sessions`;
+---------+----------------------------------+
| user_id | token                            |
+---------+----------------------------------+
|       1 | 01234567890123456789012345678901 |
+---------+----------------------------------+
|       2 | 01234567890123456789012345678902 |
+---------+----------------------------------+

How to make a selection from these three tables so that the result is like this
array
  'id' => 1
  'email' => 'email'
  'password' => 'password'
  'nickname' => 'nickname'
  'data' => 
    array
      'user_id' => 1
      'firstname' => 'firstname'
      'lastname' => 'lastname'
  'session' => 
    array
      'user_id' => 1
      'token' => '01234567890123456789012345678901'

That is, in the code it was possible to access the data like this
<?php

$result['id'];
$result['nickname'];

$result['data']['firstname'];
$result['data']['lastname'];

$result['session']['user_id'];
$result['session']['token'];

Sample query logic or something like that
select * from
  (select * from `users_sessions` where `user_id` = 1 and `token` = '01234567890123456789012345678901') as `session`,
  (select * from `users_data` where `user_id` = `session`.`id`) as `data`,
  select * from `users` where `id` = `session`.`id`

Answer the question

In order to leave comments, you need to log in

2 answer(s)
_
_ _, 2016-02-17
@t38c3j

If users, users_data and users_sessions are related one-to-one, then left join (although why not store everything in one place in this case).
If one-to-many, then on request for each table and process in code, there is no other way.

D
Dmitry Kovalsky, 2016-02-17
@dmitryKovalskiy

SELECT something FROM users as u
LEFT JOIN users_data as ud ON u.id = ud.user_id
LEFT JOIN users_sessions as us ON u.id = us.user_id

If you need users only with the available data user_data, user_sessions - change LEFT to INNER

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question