We need to make this condition:

select an id from the table, where the url is like $ a and where the same url is not like $ b

attempt such:

SELECT id FROM main WHERE url LIKE '$a%' AND url NOT LIKE '$b%' 

This query does not work correctly. = do not suggest instead of like

  • Give the query without variables, with the substituted data. - Caravus
  • 2
    Please describe the expected behavior and what you get (that is, describe what is incorrect) - Timofei Bondarev
  • Give an example of the data and describe what is wrong with your point of view. As for me, the request is completely correct. - Alex Krass

3 answers 3

http://sqlfiddle.com/#!9/055a8/3 Here is your example, what does it mean that it does not work correctly?

  • on my side, the jamb, $ a and $ b in some places changed - Rufex

The request is correct; the only thing that confuses is quotes. If this is PHP (it seems to be similar), then double quotes are needed: " , otherwise the variables are not interpolated, that is, $a% will remain so.

 $a = 'world'; print "Hello $a!"; // Hello world! print 'Hello $a!'; // Hello $a! 

    You can write quotation marks inside double quotation marks to avoid screening.

     $sql = "SELECT id FROM main WHERE url LIKE '$a%' AND url NOT LIKE '$b%'"; 

    In general, this is a bad approach. Possible sql-injection. Need so

     $conn = new PDO("mysql:host=mysql;dbname=test;", 'admin', 'admin'); $q = $conn->prepare('SELECT id FROM main WHERE url LIKE :a AND url NOT LIKE :b'); $q->bindParam(':a', "$a%", PDO::PARAM_STR); $q->bindParam(':b', "$b%", PDO::PARAM_STR); 
    • one
      why shield single quotes inside double quotes? - Rufex
    • Rufex, for sure. Stupidity wrote. Thanks, corrected. - Rjazhenka