2016-06-28 43 views
1
找到多個記錄

比方說,我有一個數組,如下所示(ID =>類型):MySQL的兩列

$contentIndexes = [ 
    32 => 'news', 
    40 => 'blog', 
    68 => 'blog', 
    109 => 'document', 
    124 => 'news' 
] 

而下面的數據庫表:

CREATE TABLE `ContentIndex` (
    `ID` INT(11) NOT NULL AUTO_INCREMENT, 
    `ItemID` INT(11) NOT NULL, 
    `ItemType` VARCHAR(50) NOT NULL COLLATE 'utf8_unicode_ci', 
    //... 
); 

我怎麼會檢索每ContentIndex基於'ItemID'和'ItemType'列的組合(最好只有一個查詢)。

使用WHERE IN是不是一種選擇,因爲它不會採取組合考慮:

ContentIndexQuery::create() 
    ->filterByItemID(array_keys($contentIndexes)) 
    ->filterByItemType($contentIndexes) 
    ->find(); 

任何想法?

回答

1

我不知道Propel語法,但基本的SQL語法將與OR

WHERE ((ItemID = 32 AND ItemType = 'news') 
     OR 
     (ItemID = 40 AND ItemType = 'blog') 
     OR 
     (ItemID = 68 AND ItemType = 'blog') 
     OR 
     (ItemID = 109 AND ItemType = 'document') 
     OR 
     (ItemID = 124 AND ItemType = 'news') 
    ) 
0

對於任何用戶的Propel遇到在未來的這個問題,這是我想出了創建一個查詢作爲Barmar說:

$items = ContentIndexQuery::create(); 
$i = 0; 

foreach ($contentIndexes as $id = > $type) { 
    if ($i > 0) $items->_or(); 

    $items->condition('cond1'.$i, ContentIndexTableMap::COL_ITEM_ID . ' = ?', $id) 
      ->condition('cond2'.$i, ContentIndexTableMap::COL_ITEM_TYPE . ' = ?', $type) 
      ->where(['cond1'.$i, 'cond2'.$i], 'AND'); 

    $i += 1; 
} 

$items = $items->find()->getData();