php - 期望多个结果时正确的 SELECT 查询

标签 php mysql

我正在尝试为我的问题提出正确的查询。基本上,如果我这样做的话,我可能会得到超过 100 个完全相同的结果:

    $query = "SELECT * FROM highway WHERE state  = 'VA'";
    $result = mysql_query($query) or die(mysql_error());
    while ($row = mysql_fetch_array($result)) {
    //code

有了这个我会得到:

    95
    95
    95
    95 (and on and on...)
    64
    64
    64 (and on and on...)

要获取的正确查询是什么:

    95
    64
    66
    81

最佳答案

您可以使用DISTINCT关键字:

The ALL and DISTINCT options specify whether duplicate rows should be returned. ALL (the default) specifies that all matching rows should be returned, including duplicates. DISTINCT specifies removal of duplicate rows from the result set. It is an error to specify both options. DISTINCTROW is a synonym for DISTINCT.

所以:

SELECT DISTINCT * FROM highway WHERE state  = 'VA'

但是,如果您的结果集在考虑某些列时有重复项,那么在我看来,您的数据库表可能设计得很糟糕。您是否进一步考虑过normalising他们?

关于php - 期望多个结果时正确的 SELECT 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7710593/

相关文章:

mysql - 检查 MySQL 中的子字符串并返回基于它的值

php - 获取 Uncaught ReferenceError : using PHP

php - 使用 OR 条件组合查询数据库

mysql - 如何通过函数方法替换mysql上任何查询中的特殊字符?

mysql - 优化与地理距离相关的 MySQL 查询

mysql - 与 MYSQL 失去连接

php - 从一个表中选择另一个表中ID等于字符串的所有字段

php - 时间轴上同一日期的 2 个元素

php - Javascript 函数在我的 Facebook 上基于 iFrame 的应用程序中不起作用/出现错误!

php - ES:匹配 bool 值和模糊查询