简体   繁体   中英

Is there a solution to compare a specific field in a SQL full-text search?

This is my regular code and it works fine:

$sql = 'SELECT '
    . '* '
  . 'FROM '
    . 'item '
  . 'WHERE MATCH '
    . '(title) '
  . 'AGAINST '
    . '(:search IN NATURAL LANGUAGE MODE) '
  . 'OR MATCH '
    . '(description) '
  . 'AGAINST '
    . '(:search IN NATURAL LANGUAGE MODE) '
  . 'ORDER BY '
    . 'id ASC';

I want to compare the field "status" to the string "public" because I need only the "public" entrys, I tried something like this:

$sql = 'SELECT '
    . '* '
  . 'FROM '
    . 'item '
  . 'WHERE MATCH '
    . '(title) '
  . 'AGAINST '
    . '(:search IN NATURAL LANGUAGE MODE) '
  . 'OR MATCH '
    . '(description) '
  . 'AGAINST '
    . '(:search IN NATURAL LANGUAGE MODE) '
  . 'WHERE '
    . 'status = "public" '
  . 'ORDER BY '
    . 'id ASC';

But with the last "WHERE" the result is nothing I expected.

Is there any solution?

You have added 2 WHERE statements, thats not allowed and when you use OR it is best to place brackets round the OR condition to ensure the correct result

$sql = 'SELECT *
        FROM item 
        WHERE status = "public"
        AND (
                MATCH (title) AGAINST (:search IN NATURAL LANGUAGE MODE) 
             OR MATCH (description) AGAINST (:search IN NATURAL LANGUAGE MODE) 
            )
        ORDER BY id ASC';

There are couple of errors in your query,

  1. WHERE clause is added twice
  2. Conditions in OR should be enclosed in round brackets '()'

     SELECT * FROM item WHERE ( MATCH (title) AGAINST (:search IN NATURAL LANGUAGE MODE) OR MATCH (description) AGAINST (:search IN NATURAL LANGUAGE MODE) ) AND status = "public" ORDER BY id ASC 

Also, using SELECT * is harmful. You can read the details about it here

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