简体   繁体   中英

Joining two tables then calculating the time difference between two columns

I have a question about a SQL query. I have two tables that I would like to compare information from. An artists table and an events table.

I have created this query to join the tables. And get the two times I am looking at.

SELECT  id_artist, full_name, event_title, events.created_at, mobile_number, email, users.created_at
FROM events   
JOIN users
  ON users.id_user = events.id_user
group by id_artist;

Is there a way to compare these two.created_at fields to see only show rows where the difference between artist creation and event creation is 3 days?

id_artist events.created_at users.created_at
1 2019-08-28 09:58:23 2019-08-29 06:35:38
2 2019-09-07 20:36:24 2019-09-13 21:29:00
3 2019-10-16 21:57:34 2019-10-16 22:12:13
4 2019-10-17 15:41:37 2019-10-17 15:38:27

Here is an example of what the data looks like. I would like there to be one more column that has the time difference in days. Then I could query this column for results greater than 3 days.

Use this:

    SELECT  id_artist, full_name, event_title,
    events.created_at, mobile_number, email, users.created_at
    FROM events   
    JOIN users
      ON users.id_user = events.id_user
    WHERE users.created_at = DATE_ADD(events.created_at, INTERVAL 3 DAY) 
    group by id_artist;

Try this query ->

SELECT ...
FROM events 
JOIN artists ON events.id_user = artists.id_use
WHERE datediff(day,artists.created_at,events.created_at) = 3

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