Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inner join two select queries on same table

Tags:

sql

I am stuck... A 'data' table with columns 'value' and 'datatype' is populated with engine load and vehicle speed and each record is stamped with date, time, lat, long. I want to query for engine load over 10% while the vehicle is moving (e.g. speed > 0). I can create a query to select the engine load and I can create a query to select the vehicle speed but how do I create a query to select engine load when > 10% AND the Vehicle is moving where their date, time lat, and long are equal?

This Query does not work, but it provides a jist of what I am trying to do. Can anyone help me create a query?

tables
TName:  data
PK  datakey
    value
fk1 dataeventkey
fk2 datatypenamekey

TName: datatypename
PK datatypenamekey
   datatypename

TName: dataevent
PK dataeventkey
   datetime
   lat
   long
SELECT 
   d1.datetime 
FROM 
    (data INNER JOIN datatypename ON data.datatypenamekey = datatypename.datatypenamekey    
    INNER JOIN dataevent ON dataevent.dataeventkey = data.dataeventkey) d1  
WHERE 
    ( d1.datatypename = "Engine Load [%]" AND d1.value > 10 )

 INNER JOIN

SELECT 
    d2.datetime  
FROM 
    (data INNER JOIN datatypename ON data.datatypenamekey = datatypename.datatypenamekey  
    INNER JOIN dataevent ON dataevent.dataeventkey = data.dataeventkey) d2  
WHERE 
    ( d2.datatypename = "Vehicle Speed [mph]" AND d2.value > 0 ) 

    ON d1.datetime = d2.datetime
like image 781
TheChrisONeil Avatar asked Jan 13 '23 18:01

TheChrisONeil


1 Answers

I'm not 100% sure I understand, but I think you just need to reference two instances of the same table. Kind of making some assumptions based on your SQL, but giving it a shot here:

SELECT 
    engineLoad.dateTime
FROM
    (
    SELECT 
       d.datakey,
       de.datetime        
    FROM 
        data d
        INNER JOIN datatypename dt ON data.datatypenamekey = dt.datatypenamekey    
        INNER JOIN dataevent de ON de.dataeventkey = d.dataeventkey  
    WHERE 
        d.value > 10 AND
        dt.datatypename = "Engine Load [%]"
    ) engineLoad
    INNER JOIN
    (
    SELECT 
       d.datakey,
       de.datetime        
    FROM 
        data d
        INNER JOIN datatypename dt ON data.datatypenamekey = dt.datatypenamekey    
        INNER JOIN dataevent de ON de.dataeventkey = d.dataeventkey  
    WHERE 
        d.value > 0  AND
        dt.datatypename = "Vehicle Speed [mph]" 
    ) vehicleSpeed 
        ON engineLoad.dataKey = vehicleSpeed.dataKey <==might need to remove this line
           AND engineLoad.datetime = vehicleSpeed.datetime

Edit Looks like you need to reference datatypename twice as well? Edited the above, so try again.

like image 87
Phil Sandler Avatar answered Jan 19 '23 12:01

Phil Sandler