Search code examples
postgresqlselectdistinctzend-db

How to build a select using Zend with a DISTINCT specific column?


I'm using Zend Framework for my website and I'd like to retrieve some data from my PostgreSQL database.

I have a request like :

SELECT DISTINCT ON(e.id) e.*, f.*, g.* FROM e, f, g
WHERE e.id = f.id_e AND f.id = g.id_f

This request works well but I don't know how to convert the DISTINCT ON(e.id) with Zend. It seems that I can get DISTINCT rows but no distinct columns.

$select->distinct()->from("e")->join("f", "e.id = f.id_e")
->join("g", "f.id = g.id_f");

Any idea on how to make a select with distinct column ?

Thanks for help


Solution

  • You probably can't do this with Zend Framework since distinct on is not part of the SQL standard (end of page in Postgres documentation). Although Postgres supports it, I would assume its not part of Zend Framework because you could in theory configure another database connection which does not offer support.

    If you know in advance that you're developing for a specific database (Postgres in this case), you could use manually written statements instead. You'll gain more flexibility within the queries and better performance at the cost of no longer being able to switch databases.

    You would then instantiate a Zend_Db_Apdapter for Postgres. There a various methods available to get results for SQL queries which are described in the frameworks documentation starting at section Reading Query Results. If you choose to go this route I'd recommend to create an own subclass of the Zend_Db_Adapter_Pgsql class. This is to be able to convert data types and throw exceptions in case of errors instead of returning ambiguous null values and hiding error causes.