简体   繁体   中英

MySQL join 2 tables with different columns

I have 2 tables ie contacts and users.

I have this query:

 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 |
+--------------------------------------+---------------+

I have the first_name, last_name from users

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

So, in the result of Assigned_to0 I require the first_name + last_name instead of id(seed_sally_id) for the first query. I'm presuming a (LEFT)JOIN statement is required here?

Thanks in advance.

John

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';

This statement do the job

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;
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;

untested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM