0

I'm trying to get rows from a table according to some basic where clauses, and now I want to include an "AND EXISTS" clause on the end. My code is the following:

$stmt = $mysqli->prepare("SELECT object_id FROM ".
          $db_table_prefix."user_events
          WHERE LPAD(start_timestamp,15,'0') < LPAD(?,15,'0')
          AND event_id = ?
          AND EXISTS ( 
            SELECT * FROM ".$db_table_prefix."user_events
              WHERE LPAD(start_timestamp,15,'0') > LPAD(?,15,'0')
              AND event_id = ? )
        ");

The problem I'm having is that I don't know how to specify a column value from the main query within the AND EXISTS subquery.

I'm looking for a way to tack on this bit into the subquery:

AND object_id = **object_id from main query**

Any help appreciated

0

3 Answers 3

1

Also, added an alias to the subquery's table to avoid confusion

$stmt = $mysqli->prepare("SELECT object_id FROM ".
      $db_table_prefix."user_events
      WHERE LPAD(start_timestamp,15,'0') < LPAD(?,15,'0')
      AND event_id = ?
      AND EXISTS ( 
        SELECT * FROM ".$db_table_prefix."user_events AS u
          WHERE LPAD(u.start_timestamp,15,'0') > LPAD(?,15,'0')
          AND u.object_id = " .$db_table_prefix.".object_id
          AND u.event_id = ? )
    ");
Sign up to request clarification or add additional context in comments.

1 Comment

This worked for me, I didn't realise you could alias in MySQL :) Many thanks
1

Rather than EXISTS, you might find a self-join syntax is clearer here, I cannot deduce exactly what you want from your code, but to get object_id for an event that started before a specific time, and was also started again later:

SELECT  ue1.object_id 
FROM    user_events ue1 join user_events ue2
WHERE   ue1.event_id = ue2.event_id AND
        ue1.object_id = ue2.object_id AND
        ue1.event_id = ? AND 
        LPAD(ue1.start_timestamp, 15, '0') < LPAD(ue2.start_timestamp, 15, '0') AND 
        LPAD(ue1.start_timestamp, 15, '0') < LPAD(?, 15, '0')

1 Comment

Sorry I should have clarified further, the second event is actually a different one (with different id) but belonging to same object. I've read that EXISTS can be time-consuming, so I will test your code as well. Many thanks
0

and object_id in (select object_id from ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.