Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query AND OR operator Logic

I'm in the middle of a project for my Comp Science project for monday, and i came across a MySQL question regarding a Query.

What I want to achieve, through words is this.

If the column to=jake and column from=connor OR column to=connor and column from=jake get the cID from that specific table.

What I have so far is this

 $query="SELECT cID FROM conversation WHERE to='$to' AND to='$from' OR to='$from' AND        from='$to'";

What is there that I can do to get this query to work? Thanks in advance!

like image 952
ronnockoch Avatar asked Jun 16 '12 22:06

ronnockoch


2 Answers

You just need a couple pairs of () to group the two conditional pairs, separated by a logical OR

$query="
  SELECT cID 
  FROM conversation
  WHERE 
      /* to Jake, from Connor */
     (`to`='$to' AND `from`='$from')
      /* OR to connor, from jake */ 
     OR  (`to`='$from' AND `from`='$to')";

Note: FROM and TO are both MySQL reserved keyword, and thus require quoting with backticks.

like image 181
Michael Berkowski Avatar answered Sep 30 '22 20:09

Michael Berkowski


This is untested but I would think you need to put the to='$to' AND to='$from' (which should be from not to i guess??) into brackets??

Just realised someone else put this as i was typing it

like image 32
Stefan Avatar answered Sep 30 '22 21:09

Stefan