Search code examples
phalcon

How can I use NOT BETWEEN in a query in Phalcon?


I am making a query using NOT BETWEEN using Phalcon Query Language (PHQL), but it is not working the application hangs. Someone could give me an idea of ​​how I could do it. Thank you very much. There is my query.

       $sql = "SELECT c.* FROM table as c 
      WHERE not exists c.activated NOT BETWEEN :f1: and :f2: ";
        $parameters['f1'] = '2017-10-01';
        $parameters['f2'] = '2017-10-05';
        $result= $this->modelsManager->executeQuery($sql, 
        $parameters);

every time the query is run this leaves:

Warning: session_destroy(): Trying to destroy uninitialized session in C:\xampp\htdocs\myapp\app\plugins\SecurityPlugin.php on line 222


Solution

  • I have never heard of Phalcon Query Language (PHQL) until I opened this question, but the syntax you are attempting isn't valid in SQL. Try this instead:

    $sql = "SELECT c.* FROM table as c WHERE NOT c.activated BETWEEN :f1: and :f2: ";
        $parameters['f1'] = '2017-10-01';
        $parameters['f2'] = '2017-10-05';
        $result= $this->modelsManager->executeQuery($sql, 
        $parameters);
    

    NOT ( your_predicate_here )

    All you need is the NOT to reverse the true/false values being returned by the predicate. e.g. if a date IS between the dates (true), reverse that to false so it is equivalent to "not between".

    SQL Fiddle

    MySQL 5.6 Schema Setup:

    CREATE TABLE Table1
        (`activated` datetime)
    ;
    
    INSERT INTO Table1
        (`activated`)
    VALUES
        ('2016-12-01 00:00:00'),
        ('2017-10-01 00:00:00'),
        ('2017-10-05 00:00:00')
    ;
    

    Query 1:

    SELECT c.* 
    FROM table1 as c 
    WHERE NOT c.activated BETWEEN '2017-10-01' AND '2017-10-05'
    

    Results:

    |            activated |
    |----------------------|
    | 2016-12-01T00:00:00Z |