Does Drupal support DISTINCT ON (field1, field2)

Events happening in the community are now at Drupal community events on www.drupal.org.
Posted by mariacha1 on December 19, 2013 at 12:23am

Hi guys,

I'm new to postgreSQL in Drupal and can't figure out how to do a DISTINCT ON select within drupal's query classes with declared fields like this:

SELECT DISTINCT ON (field1, field2) field1, field2, field3 FROM table1

I see you can set a query as $query->distinct(TRUE) but that just seems to add the word DISTINCT, which if I understand it, just makes sure that all columns combined are unique.

Is this possible to pass those DISTINCT ONs to a funciton or should I rewrite my query to do it some other way?

Categories:

Comments

Db query

Posted by metzlerd on December 19, 2013 at 2:09pm

The database api doesn't support all syntaxes since they aren't available in all databases, however if you don't need to build the query dynamically consider using db_query() instead of db->select. If you use db_query you can use whatever postgres syntax you need.

Extender

Posted by mradcliffe on December 19, 2013 at 3:08pm

I like to maintain compatibility with as many databases as possible in my code. The other way of doing this, is to write a Query Extender class for DistinctOn.

You could also write database specific implementations that use MySQL's "group by" to support MySQL as well.

Db query

Posted by metzlerd on December 19, 2013 at 2:24pm

Woops duplicate....deleting.

Db query

Posted by metzlerd on December 19, 2013 at 2:25pm

Woops duplicate deleting.

Thanks for the advice

Posted by mariacha1 on December 19, 2013 at 6:01pm

I ended up doing a really hacky thing and adding the DISTINCT ON as an expression like so:

$query->addExpression('DISTINCT ON (field1, field2) field1', 'field1');

Which produces
SELECT DISTINCT ON (field1, field2) field1 as field1, field2, field3 FROM table1

But I think the QueryExtend for DistinctOn is the correct way to go about it. I'm just suprised such a thing doesn't exist already! I'll post back if I get it working.

Did you ever get this

Posted by liam morland on May 24, 2024 at 3:59pm

Did you ever get this working?

Postgresql

Group organizers

Group notifications

This group offers an RSS feed. Or subscribe to these personalized, sitewide feeds:

AltStyle によって変換されたページ (->オリジナル) /