Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two conditions in a where clause?

I have the following:

time_range = (1.month.ago.beginning_of_month..1.month.ago.end_of_month)  Comment.where(:created_at => time_range).count 

How can I add to the where clause with a statement like:

.where("user_id is not in (?)",[user_ids]). 

How can I combine the two? Thanks

like image 445
AnApprentice Avatar asked May 16 '12 03:05

AnApprentice


People also ask

How do I combine two conditions in SQL?

Syntax. SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]... AND [conditionN]; You can combine N number of conditions using the AND operator.

Can we use WHERE clause two times in SQL?

But yes, you can use two WHERE.

Can we join two tables on two conditions?

The SQL JOIN is an important tool for combining information from several tables. Most often, you'll be joining tables based on a primary key from one table and a foreign key from another table. However, it is also often the case that you need to join tables by two or more columns.


2 Answers

if you want a "AND" conditional query, try this:

Comment.   where(:created_at => time_range).   where("user_id is not in (?)",[user_ids]) 

which will produce SQL like : select ... where ... AND ...

if you want the WHERE clause more complicated, such as: where ( a AND b) OR (c AND d), you have to combine the conditions into the clause yourself, e.g.

Comment.where("(a AND b ) OR (c AND d)") 
like image 140
Siwei Avatar answered Oct 06 '22 03:10

Siwei


User.where(["name = ? and email = ?", "Joe", "[email protected]"]) 

This will be fine.

like image 42
Sujith Sudersan Avatar answered Oct 06 '22 03:10

Sujith Sudersan