MySQL连接2个具有不同列的表

时间:2014-06-30 06:29:03

标签: mysql

我有2个表,即联系人和用户。

我有这个问题:

 SELECT contacts.id AS 'contacts_id', contacts.assigned_user_id AS 'Assigned_to0' FROM  contacts  WHERE contacts.date_entered < DATE_ADD(NOW(), INTERVAL + 15 day) AND contacts.deleted = 0 limit 1;
+--------------------------------------+---------------+
| contacts_id                          | Assigned_to0  |
+--------------------------------------+---------------+
| cdb8dae0-eb8b-bd1e-5667-53984aa7a5dd | seed_sally_id |
+--------------------------------------+---------------+

我有来自用户的first_name,last_name

select id,first_name,last_name from users where id='seed_sally_id';
+---------------+------------+-----------+
| id            | first_name | last_name |
+---------------+------------+-----------+
| seed_sally_id | Sally      | Bronsen   |
+---------------+------------+-----------+

因此,在 Assigned_to0 的结果中,我需要第一个查询的first_name + last_name而不是id(seed_sally_id)。 我假设这里需要一个(LEFT)JOIN语句?

提前致谢。

约翰

3 个答案:

答案 0 :(得分:1)

SELECT contacts.id AS 'contacts_id',
       concat(users.first_name,' ' ,users.last_name) as Assigned_to0
FROM contacts
INNER JOIN users ON contacts.assigned_user_id=users.id
WHERE contacts.date_entered < DATE_ADD(NOW(), INTERVAL + 15 DAY)
  AND contacts.deleted = 0
  AND users.id='seed_sally_id';

答案 1 :(得分:0)

此声明完成工作

SELECT contacts.id AS 'contacts_id', contacts.assigned_user_id AS 'Assigned_to0' , users.first_name, users.last_name
FROM  contacts  join users on contacts.Assigned_to0  =users.id
WHERE contacts.date_entered < DATE_ADD(NOW(), INTERVAL + 15 day) AND contacts.deleted = 0 limit 1;

答案 2 :(得分:0)

SELECT c.id AS 'contacts_id', c.assigned_user_id AS 'Assigned_to0',
       u.first_name, u.last_name
FROM contacts c, users u
WHERE c.deleted = 0
  AND c.assigned_user_id=u.id
  AND c.date_entered < DATE_ADD(NOW(), INTERVAL + 15 DAY)
  AND u.id='seed_sally_id' limit 1;

未测试