简体   繁体   中英

Multiple columns in a WHERE clause

I'm trying to make a url query string where you enter a parameter and it searches my MySQL database(stored quotes from an irc channel) for one random quote with a variable entered in LIKE at a time but having trouble getting it to search more than one column with the query I'm using. The two fields in the table I want it to search in were "title" and "quote". Is there a better way of doing this? Right now i just have it going to a page to confirm output for now for testing purposes. The code below works fine as is if just searching the "title" or "quote" field alone.

app.get("/api", function(req, res){

    var search = "%" + req.query.search + "%";
    var queryString = "SELECT * FROM quotes WHERE title LIKE ? ORDER BY RAND() LIMIT 1";
    var queryString =  mysql.format(queryString, search);
    mysqlPool.getConnection(function(err, connection) {
        if(err) throw err;
        connection.query(queryString, function(err, rows, fields){
            if (!err){
                res.send('<xmp>' + JSON.stringify(rows[0], null, 2) + '</xmp>');
                connection.release();
            } else {
                console.log('Error while performing Query.');
                connnection.release();
            }
        });
    });
});

I tried doing this below but obviously isn't working:

var queryString = "SELECT * FROM quotes WHERE (title OR quote) LIKE ? ORDER BY RAND() LIMIT 1";

example of the output with just "title" searched here just to get an idea:

{
  "id": 3947,
  "nick": "o_O",
  "host": "o_O``!~o_O@*.ma.cable.rcn.com",
  "title": "gix.flesh.eating.bacteria",
  "quote": "<gix> omg my face is like 10lbs lighter",
  "channel": "#motorcycles",
  "timestamp": 1205791192
}

您不能LIKE这样使用LIKE ,请尝试此;)

var queryString = "SELECT * FROM quotes WHERE title LIKE ? OR quote LIKE ? ORDER BY RAND() LIMIT 1";

Every condition in your WHERE-Clause must be True. You are checking the title OR quote . If condition A is met in an OR it exits and doesn't check the second condition. You could check it like:

WHERE
    (
     title like ? 
       and 
       quote like?
    OR
     (
        (title or quote) like ?
      )
    )

This resolves like

  1. title contains ? And quote contains?

    Yes: return row No: GoTo2. The inner ( )

    1. Any of those two fields contain the value ?

Yes: return row No: don't return row

Hope this clears it up a bit.

Best regards,

Georg

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