【问题标题】:MySQL: How to get distinct name but also by state?MySQL:如何获得不同的名称以及状态?
【发布时间】:2014-11-07 17:12:02
【问题描述】:

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

//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.. 但如果它们有不同的状态.. 它不会考虑到这一点。

示例数据结构:

加利福尼亚州约翰·多伊

加利福尼亚州约翰·多伊

加利福尼亚州约翰·多伊

Jane Doe CA

Jane Doe CA

纽约约翰·多伊

纽约约翰·多伊

Jenny Doe WI

比利鲍勃 PA

比利鲍勃 PA

约翰·多瓦

彼得保罗佛罗里达州

彼得保罗佛罗里达州

彼得保罗佛罗里达州

彼得保罗佛罗里达州

在我的桌子上..

我希望它只返回 1 个 John Doe(针对 CA)......但也返回 John Doe NY(1 次)和 John Doe WA(1 次)......好吧,他只在那里一次..但你明白了:)

现在,我只会让 John Doe 返回 1 次..(我相信必须取表中找到的第一个)

我希望在哪里获得“3”约翰·杜斯返回..

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

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

【问题讨论】:

标签: php mysql distinct


【解决方案1】:

如果状态在您的表中,这将起作用。只需将状态添加到您的 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

【讨论】:

  • 虽然我很欣赏这个链接,但它没有上下文。汤姆发布的正是我所做的:GROUP BY first,last,state
猜你喜欢
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
  • 1970-01-01
  • 2015-10-13
相关资源
最近更新 更多