MySQL将查询别名用于另一个查询

时间:2016-06-04 06:20:48

标签: mysql temp-tables

我的头衔不是很好,但让我解释一下我的情况。我有一个jobs表。 jobs表有2个外键到users表:sales_rep_idaccount_manager_id

然后我有另一个名为contact_info的表,它与users表有一对一的关系。

jobs
-----
sales_rep_id
account_manager_id
...

users
-----
first_name
last_name

contact_info
-----
user_id
home_phone

如果我想查询每个工作的两个人的电话号码,我会执行以下操作:

SELECT reps.home_phone as reps_home, account_managers.home_phone as a_m_home FROM jobs
JOIN 
  (SELECT * FROM users 
   JOIN contact_info 
   ON users.id = contact_info.user_id) reps
ON reps.id = jobs.sales_rep_id
JOIN 
  (SELECT * FROM users 
   JOIN contact_info 
   ON users.id = contact_info.user_id) account_managers
ON account_managers.id = jobs.account_manager_id

有什么办法可以用连接的数据创建临时表吗?这种加入最有效的方法是什么?例如,如果我在jobs表中有10个外键到users表,我需要所有10个的phone_number呢?

2 个答案:

答案 0 :(得分:3)

这应该是您需要的所有信息

SELECT j.*
 , u1.first_name as sales_rep_first_name
 , u1.last_name as sales_reps_last_name
 , u2.first_name as manager_first_name
 , u2.u1.last_name as manager_last_name
 , c1.home_phone as sales_rep_home_phone
 , c2.home_phone as manager_home_phone
FROM jobs as j
INNER JOIN contact_info as c1 ON j.sales_rep_id = c1.user_id
INNER JOIN user u1 ON u1.id= c1.user_id
INNER JOIN contact_info as c2 ON j.saccount_manager_id = c2.user_id
INNER JOIN user u2 ON u2.id= c2.user_id;

答案 1 :(得分:1)

定义加入usercontact_info的视图。

CREATE VIEW user_contact_info
SELECT u.id, u.first_name, u.last_name, c.home_phone
FROM user AS u
JOIN contact_info AS c ON u.id = c.user_id

然后你可以像使用它一样使用它。

SELECT reps.home_phone as reps_home, account_managers.home_phone as a_m_home 
FROM jobs
JOIN user_contact_info AS reps ON reps.id = jobs.sales_rep_id
JOIN user_contact_info AS account_managers ON account_managers.id = jobs.account_manager_id