【问题标题】:MySQL find multiple records by two columnsMySQL通过两列查找多条记录
【发布时间】:2016-06-28 20:51:36
【问题描述】:

假设我有一个如下数组(ID => 类型):

$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',
    //...
);

我将如何根据“ItemID”和“ItemType”列的组合检索每个ContentIndex(最好只使用一个查询)。

使用WHERE IN 不是一个选项,因为它不会考虑组合:

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

有什么想法吗?

【问题讨论】:

    标签: php mysql multiple-columns propel


    【解决方案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')
          )
    

    【讨论】:

      【解决方案2】:

      对于将来遇到此问题的任何 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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-15
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 2016-11-13
        相关资源
        最近更新 更多