来自更多表的Mysql查询

时间:2017-07-17 07:14:56

标签: mysql

我有这个数据库表结构:

用户

+----+--------------+-----------------+
| id | name         | last_name       |
+----+--------------+-----------------+
| 1  |Matteo        |Del Mastro       |
| 2  |Giovanni      |Di Genova        |
| 3  |Francesco     |Moccia           |
| 4  |Vincenzo      |Rossi            |
+----+--------------+-----------------+

user_extra

+----+--------------+-----------------+
| id | user_id      | phone           |
+----+--------------+-----------------+
| 1  |1             |3632562352       |
| 2  |2             |3684647333       |
| 3  |3             |3638543262       |
| 4  |4             |3633364655       |
+----+--------------+-----------------+

company_users

+----+--------------+-----------------+----------+
| id | company_id   | dipartimento_id | user_id  |
+----+--------------+-----------------+----------+
| 1  |1             |1                | 1        |
| 2  |1             |2                | 2        |
| 3  |1             |3                | 3        |
| 4  |1             |3                | 4        |
+----+--------------+-----------------+----------+

dipartimenti

+----+--------------+-----------------+-------------+
| id | sub_id       | company_id      | name        |
+----+--------------+-----------------+-------------+
| 1  |NULL          |1                |Comando      |
| 2  |1             |1                |Sez. Analisi |
| 3  |2             |1                |NIL Roma     |
| 4  |2             |1                | NIL Latina  |
+----+--------------+-----------------+-------------+

现在,我需要选择具有相同company_id和相同部门的所有用户(按部门分组)

SELECT SQL_CALC_FOUND_ROWS User。,CompanyUser。,UserExtra。*,CompanyDipartimenti.id,Comp anyDipartimenti.name FROM users AS User LEFT JOIN company_users AS CompanyUser ON(User.id = CompanyUser.user_id) LEFT JOIN user_extras AS UserExtra ON(User.id = UserExtra.user_id)LEFT JOIN dipartimentis AS CompanyDipartimenti ON(CompanyUser.dipartimento_id = CompanyDipartimenti.id OR CompanyUser.dipartimento_id = CompanyDipartimenti.sub_id)WHERE 1 AND CompanyUser.company_id ='1'GROUP BY CompanyUser.id,CompanyUser.dipartimento_id ORDER BY User.dt_last_login DESC LIMIT 0,50

0 个答案:

没有答案