【问题标题】:Select one row without duplicate entries keyword based选择一行没有重复条目的关键字
【发布时间】:2018-03-14 16:45:21
【问题描述】:

我的info 表有以下列:

Id | Name | City | date | status

我想从info 中选择所有名称,并使用以下查询:

$query = mysql_query("SELECT name FROM info WHERE status = 1 ORDER BY id") 
         or die(mysql_error());

while ($raw = mysql_fetch_array($query)) 
{
  $name = $raw["name"];
  echo ''.$name.'<br>';
}

名称列内容示例:

alex
alex1
alex2
michel22
michel33
michel44

嗯,结果是它返回了所有条目。我想回显所有不重复但只有内容指定关键字的条目

说:在原始name 下,我们以不同的格式插入了名称“alex and michel”10 次。

我只想回声:

alex
michel

一次可能吗?

【问题讨论】:

  • 警告:如果您只是学习 PHP,请不要学习过时的 mysql_query 接口。这很糟糕,已在 PHP 7 中删除。PDO is not hard to learn 之类的替代品和PHP The Right Way 之类的指南有助于解释最佳实践。确保确保您的用户参数为properly escaped,否则您将得到严重的SQL injection bugs
  • 您希望您的代码通过什么逻辑来识别['alex', 'alex1', 'alex2'] 都应该被视为等效?根据您的示例数据,您可以去掉所有数字并只保留字母字符吗?那就足够了吗? (如果您不知道如何手动操作,那么您将永远无法让计算机自动完成。)

标签: php mysql sql


【解决方案1】:

首先使用 mysqli 或 pdo 来连接你的数据库。 mysql 已弃用。

$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result = mysqli_query($mysqli,"SELECT name FROM info WHERE status = 1 ORDER BY id") or die(mysqli_error($mysqli));

$uniqueNames = array();
while ($row = mysqli_fetch_assoc($result)) {
    $nameWithoutNumbers = preg_replace('/[0-9]+/', '', $row["name"]); //removes the numbers and leave only names
    $uniqueNames[$nameWithoutNumbers] = 1; //just a filtering hack, if key exits value is replaced otherwise a new key is created
}
foreach($uniqueNames as $name => $one)
    echo $name; //remember you were saving your names as keys pointing to 1s

【讨论】:

    猜你喜欢
    • 2011-10-25
    • 1970-01-01
    • 2023-03-10
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    相关资源
    最近更新 更多