繁体   English   中英

MySQL:如何获得唯一的名称,但也要按州?

[英]MySQL: How to get distinct name but also by state?

我的当前查询正在运行,这是我当前的方法:

//loop through the defined fields & build query
foreach($searchFields as $searchField){
    // if the field is set and not empty
    if(isset($_POST[$searchField]) && $_POST[$searchField] != '') {
        // create a new condition while escaping the value inputed by the user (SQL Injection)
        $searchConditions[] = "`$searchField` LIKE '%" . $_POST[$searchField] . "%'";
    }
}

//build the query
//$getExperts_sql = "SELECT * FROM $tablename";
$getExperts_sql = "SELECT *, COUNT(*) as casecount FROM $tablename";

// if there are conditions defined
if(count($searchConditions) > 0) {
    // append the conditions
    $getExperts_sql .= " WHERE " . implode (' AND ', $searchConditions) ." GROUP BY first,last"; // you can change to 'OR', but I opt'd to apply the filters cumulative
}

如前所述,它正在工作..(它应该如此)..但是我需要帮助来获得更多粒度/特定信息。

按照它的样子..它-仅选择唯一/唯一的名称...(这是我需要的)..但是我还需要添加另一段数据以“与众不同”(如果有意义)

当前..如果我有重复的名称记录..它仅返回1 ..但是如果它们具有不同的状态..则不考虑这一点。

示例数据结构:

约翰·杜伊

约翰·杜伊

约翰·杜伊

简·多伊(CA)

简·多伊(CA)

纽约州约翰·杜

纽约州约翰·杜

詹妮·威

比利·鲍勃·PA

比利·鲍勃·PA

约翰·杜

彼得·保罗

彼得·保罗

彼得·保罗

彼得·保罗

在我的桌子上..

我希望它只返回1个John Doe(对于CA)...而且还返回John Doe NY(1次),以及John Doe WA(1次)...那么,他只在那儿一次。你明白了:)

目前,我只会让John Doe退回1次。(必须相信我相信表格中的第一个)

我希望在哪里获得“ 3”的约翰·杜尔斯回来了..

我想我正在寻找一个与众不同的名称和州? 在一起?...但是不确定如何更改当前查询以到达那里。

我不能只在名字/姓氏上使用DISTINCT ..我也不能只在状态上使用它。

如果状态在您的表中,这将起作用。 只需将状态添加到您的“ Group By依据”语句即可。

$getExperts_sql .= " WHERE " . implode (' AND ', $searchConditions) ." GROUP BY first,last, state"; // you can change to 'OR', but I opt'd to apply the filters cumulative

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM