简体   繁体   中英

Computing additional column in SQL SELECT statement using data from different tables

I appreciate a help producing a proper query that does the following.

I have table 1 like this:

TIME              DATA    PRESSURE
2015-03-01 12:00  213.2   222
2015-03-01 12:01  203.2   222

and table 2

TIMESTART            TIMEEND               CORRECTIONFACTOR
2014-01-01 00:00:00  2015-01-01 00:00:00   1.1234
2015-01-01 00:00:00  2016-01-01 00:00:00   1.1234

I need inside SQL SELECT query for Table 1 (SELECT * FROM table1) generate additional column that defined as such:

CORRECTED = DATA* PRESSURE^CORRECTIONFACTOR,

where CORRECTIONFACTOR is obtained from Table 2 correctly for TIME that falls in the TIMESTART-TIMEEND interval (TIMESTART inclusive and TIMEEND exclusive). How could I do that?

Use simple JOIN as follows:

SELECT t1.time, t1.data * t1.pressure ^ t2.correctionfactor AS result
FROM table1 t1
JOIN table2 t2 ON t1.time >= t2.timestart AND t1.time < t2.timeend

Note that you can't use expr BETWEEN min AND max as it's inclusive.

https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_between

Not sure what's the intention of ^ operator in the question. In MySQL it represents bitwise XOR. If you wanted a power of, use POW() then.

https://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_pow

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