Mysql选择具有唯一字段值计数的查询

时间:2017-11-24 15:56:19

标签: mysql mysqli

我的查询是从数据库中获取联系人:

$contacts = $dbh->prepare("
SELECT r.title region_title
     , c.title
     , c.region_id
     , c.id
     , c.catalog_id
     , c.address
     , c.phone
     , c.email
     , c.website
     , c.category_title
     , c.subcategory_title
     , c.subcategory_id
     , c.manufacturer 
  FROM contacts c 
  LEFT 
  JOIN regions r 
    ON c.region_id = r.id 
 WHERE manufacturer = 1 
   AND region_id IN (".implode(',', $regions).") 
   AND subcategory_id IN (".implode(',', $categories).")
");

获取联系人列表,购买region_title

$contacts->fetchAll(PDO::FETCH_GROUP)

结果是:

array() {
  ["First region title"]=>
  array() {
    contact1
    contact2
    ...
  },
  ["Second region title"]=>
  array() {
    contact3
    contact4
    ...
  }
}

如何在同一查询中获取唯一c.catalog_id字段的数量?

1 个答案:

答案 0 :(得分:0)

您可以通过catalog_id灌输获取唯一的catalog_id字段,并设置如下条件:

$contacts = $dbh->prepare("
SELECT r.title region_title
 , c.title
 , c.region_id
 , c.id
 , c.catalog_id
 , c.address
 , c.phone
 , c.email
 , c.website
 , c.category_title
 , c.subcategory_title
 , c.subcategory_id
 , c.manufacturer 
 FROM contacts c 
LEFT 
  JOIN regions r 
ON c.region_id = r.id 
 WHERE manufacturer = 1 
 AND region_id IN (".implode(',', $regions).") 
 AND subcategory_id IN (".implode(',', $categories).")
 GROUP BY catalog_id HAVING COUNT(catalog_id)=1
");