簡體   English   中英

如何在 Zend 框架中使用 GROUP_CONCAT?

[英]How to use GROUP_CONCAT with Zend Framework?

假設我有一張桌子:學生

______________________________________________________
|id   | name           | school        | class        |
______________________________________________________
| 1   | John           | ABC           | C1           |
| 2   | Jack           | ABC           | C1           |
| 3   | Anna           | ABC           | C1           |
| 4   | Peter          | DEF           | D1           |
| 5   | Alex           | ABC           | C2           |
| 6   | Bryan          | ABC           | C2           |
| 7   | David          | ABC           | C2           |
| 8   | Cristian       | DEF           | D1           |
_______________________________________________________

使用此查詢:

 SELECT a.class,GROUP_CONCAT(a.name) as names FROM students a WHERE a.school='ABC' GROUP BY a.class 

給我這個結果:

 ____________________________
|class  | names             |
 ____________________________
| C1    | John, Jack, Anna  |
| C2    | Alex, Bryan, David|
 ____________________________

如何在 Zend Framework 中使用 Zend_Db_Table 或 Zend_Db_Select 執行此查詢? 太感謝了!

我想它會是這樣的。 試試看。

$table = Your_DbTable_Class();
$select = $table->select()
          ->setIntegrityCheck(false)
          ->from(array('a' => 'students'), array( 'class' => 'class' , 'names' => new Zend_Db_Expr('GROUP_CONCAT(a.name)')) )
          ->where( 'a.school = ?', 'ABC' ) 
          ->group('a.class');

當我組裝它時,它給了我以下查詢:

SELECT `a`.`class`, GROUP_CONCAT(a.name) AS `names` FROM `students` AS `a` 
WHERE (a.school = 'ABC')
GROUP BY `a`.`class`

是你要找的嗎?

Zend Expression 給了我一些問題,對我來說最簡單的方法是:

$select->from($this,
    array(
         'listings.*',
         '(SELECT GROUP_CONCAT(DISTINCT ecg.listing_cat_name,"*|*",ecg.listing_cat_id SEPARATOR "-|-") FROM listings_cats AS ecg 
LEFT JOIN listings_to_listings_cats ON listings_to_listings_cats.listing_cat_id=ecg.listing_cat_id
WHERE listings_to_listings_cats.listing_id=listings.listing_id
LIMIT 7 ) AS catGrouping'))

在這里,我連接了一個類別名稱和 ID 列表,我在搜索結果中展開並打印每個父記錄的可點擊子類別列表。 您顯然可以向 from() 添加進一步的連接和其他條件,因為上面將被視為子查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM