Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 2 fields in Drupal

I want to do a simple SQL query in Drupal, but I'm not sure how. I would like to achieve this:

SELECT COUNT(nid) AS i_count FROM node WHERE `created` != `changed`;

I have the following code, which doesn't work:

$query = db_select('node', 'n');
$query->addExpression("COUNT(nid)","i_count");
$query->condition("created","changed","!=");
$i_number_published = $query->execute()->fetchCol();

The reason why it doesn't work is that it compares the column created with the string value "changed". Is there any way I can tell it to compare columns instead of column-string?

like image 666
Eduard Luca Avatar asked Feb 21 '26 03:02

Eduard Luca


1 Answers

Use the where() member function to add conditions based on other fields in the table:

$query = db_select('node', 'n');
$query->addExpression("COUNT(nid)","i_count");
$query->where("created != changed");
$i_number_published = $query->execute()->fetchCol();
like image 132
Clive Avatar answered Feb 23 '26 15:02

Clive