如何使用dql从数据表中获取唯一值?

Moh*_*ain 11 mysql doctrine dql

我有一个表,其中存在一个列,其中存储了各种值.我想使用dql从该表中检索唯一值.

         Doctrine_Query::create()
                    ->select('rec.school')
                    ->from('Records rec')                   
                    ->where("rec.city='$city' ")                                    
                    ->execute();        
Run Code Online (Sandbox Code Playgroud)

现在我只想要唯一的价值观.谁能告诉我怎么做......

编辑

表结构:

CREATE TABLE IF NOT EXISTS `records` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
 `city` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
 `school` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16334 ;
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的查询:

   Doctrine_Query::create()
          ->select('DISTINCT rec.city')
          ->from('Records rec')                   
          ->where("rec.state = '$state'")                                    
             // ->getSql();
           ->execute();                 
Run Code Online (Sandbox Code Playgroud)

为此创建Sql给了我:

SELECT DISTINCT r.id AS r__id, r.city AS r__city FROM records r WHERE r.state = 'AR'
Run Code Online (Sandbox Code Playgroud)

现在检查生成的sql :::: DISTINCT在'id'列上,因为我想在城市列上区分.任何人都知道如何解决这个问题.

EDIT2

Id是独特的,因为它是一个自动增量值.我在城市列中有一些真正的重复:德里和德里.对..现在,当我试图从中获取数据时,我正在两次获得德里.我该如何进行这样的查询:

  select DISTINCT rec.city where state="xyz";
Run Code Online (Sandbox Code Playgroud)

因为这会给我正确的输出.

EDIT3:

谁能告诉我如何弄清楚这个查询.. ???

cb0*_*cb0 15

取决于你使用的是什么版本,但我遇到了同样的问题 - > distinct()对我有用.

Doctrine_Query::create()
      ->select('rec.city')->distinct()
      ->from('Records rec')                   
      ->where("rec.state = '$state'")                                    
       ->execute();     
Run Code Online (Sandbox Code Playgroud)

  • 除非您想真正轻松地对网络进行黑客攻击(SQL注入),否则请不要使用诸如`-> where(“ rec.state ='$ state'”)`之类的未转义查询参数。而是使用安全参数:`-> where('rec.state =:state')-> setParameter('state',$ state)` (3认同)

m14*_*14t 5

你能用GROUP BY吗?

Doctrine_Query::create()
    ->select('rec.school')
    ->from('Records rec')                   
    ->where("rec.city='$city' ")                                    
    ->groupBy('rec.school')   
    ->execute();
Run Code Online (Sandbox Code Playgroud)