C
C
cjitkul332017-03-16 10:29:43
MySQL
cjitkul33, 2017-03-16 10:29:43

How to make a tricky join in MySQL?

There is table1 where the fields

  1. username (varchar)
  2. dt (timestamp)
  3. value (varchar)

There is table2, where the fields
  1. username (varchar)
  2. dt (timestamp)
  3. value (varchar)

How to select the value from table1 with the least resources (i.e. the most optimal) and complement them with value from table2 where the date-time will be closest to the date-time from table1?
those. more or less like this:
SELECT table1.username, table1.dt, table1.value, table2.value 
FROM table1, table2 
WHERE table1.username = table2.username and table1.dt БЛИЖАЙШАЯ_К table2.dt

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alpeg, 2017-04-09
@alpeg

SELECT `table1`.`username`, `table1`.`dt`, `table1`.`value`, (
  SELECT `table2`.`value`
  FROM `table2`
  WHERE `table1`.`username` = `table2`.`username`
  ORDER BY ABS(TIMESTAMPDIFF(SECOND, `table1`.`dt`,`table2`.`dt`)) ASC
  LIMIT 1
) AS `t2value`
FROM `table1`

Alas, this does not smell of efficiency - EXPLAIN says that the subquery will contain " Using where; Using temporary; Using filesort " even with indexes on the `dt` fields - i.e. for each username from the first table, the calculation of the time difference with each record with the same username from table 2 will be performed.
Although, if there are not 10+ records for each username in the table, then it will still be tolerable.
And, for God's sake, use a normal JOIN instead of table1,table2.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question