问题
I want to select distinct year from mysql database using doctrine:
it is easy to do this using mysql
SELECT DISTINCT DATE_FORMAT( year , '%Y') as dates FROM Inscription
i don't find how to do this in doctrine documentation, anyone can help?
回答1:
The SQL statement SELECT DISTINCT DATE_FORMAT( year , '%Y') as dates FROM Inscription
can be written in Doctrine as follows:
A. If you are writing a table method:
class InscriptionTable extends Doctrine_Table {
/* ... */
public function getDistinctYears()
{
return $this->createQuery('I')
->select('DISTINCT(DATE_FORMAT( year , '%Y')) years')
->setHydrationMode(Doctrine::HYDRATE_ARRAY)
->execute();
}
}
B. If you are writing an inline DQL call:
InscriptionTable::getInstance()->createQuery('I')
->select('DISTINCT(DATE_FORMAT( year , '%Y')) years')
->setHydrationMode(Doctrine::HYDRATE_ARRAY)
->execute();
回答2:
If you want this with Doctrine 2 you can use this extension:
Guide: http://www.uvd.co.uk/blog/labs/using-mysqls-date_format-in-doctrine-2-0
The code: https://github.com/uvd/Doctrine
it works great for me
回答3:
Never use distinct, always use group by instead when you can, like this:
SELECT DATE_FORMAT( year , '%Y') as dates
FROM Inscription
GROUP BY dates
Doctrine documentation on group by is easy to find I think.
回答4:
If you use Postgresql, you will receive:
select('SUBSTRING(offer.date_closed, 0, 5)')
function substr(timestamp without time zone integer integer) does not exist
Use instead:
select('SUBSTRING(CONCAT(offer.date_closed, \'\'), 0, 5)')
来源:https://stackoverflow.com/questions/10768347/select-distinct-year-doctrine