【问题标题】:mysql SELECT distinct row from col1 WHERE col2=xmysql SELECT distinct row from col1 WHERE col2=x
【发布时间】:2013-02-28 09:27:51
【问题描述】:

我试图从 'Specifically' 中选择不同的名称,但仅限于 col Type = 特定值的地方。

例如我有

rowID    Type   Specifically
1        cat    Ocicat
2        cat    Bombay
3        cat    Bombay
4        cat    Bengal
5        cat    Savannah
6        dog    Collie
7        dog    Keeshond
8        dog    Pug
9        dog    Keeshond
10       dog    Pug
11       dog    Doberman
12       Horse  n/a

我想读出类似

的内容
type=cat and specific=Bengal
type=cat and specific=Bombay
type=cat and specific=Ocicat
type=cat and specific=Savannah

我目前有这个,但它给了我“未定义的索引:类型”

$Result = mysql_query("select distinct Specifically from pet_table WHERE Type='cat' ORDER BY Specifically asc ");

while($row = mysql_fetch_array($Result)) 
{
PRINT("type=".$row['Type']." and specific=".$row['Specifically']."<BR>");
}

我也想做一些类似 Type 不是 cat OR dog OR horse... 等的事情

谢谢

【问题讨论】:

    标签: php mysql distinct


    【解决方案1】:

    索引不存在,因为您没有选择它。在您的 SELECT 语句中包含 Type 以修复它。

    【讨论】:

      【解决方案2】:

      您收到未定义索引错误,因为您没有获取 Type 列,而是尝试使用它。

      将您的查询更改为。

      select type, distinct Specifically from pet_table 
      WHERE Type='cat' ORDER BY Specifically asc
      

      其次,如果你不想输入猫狗马,你可以使用NOT IN子句。

      最后,请不要使用 MySQL,因为它没有维护并且已被弃用。考虑使用 MySQLi 或 PDO。

      【讨论】:

        【解决方案3】:

        你想要 GROUP BY

        SELECT Type, Specifically FROM pet_table
          WHERE Type='cat'
          GROUP BY Specifically
          ORDER BY Specifically asc
        

        【讨论】:

        • 他还需要Type 专栏
        【解决方案4】:

        您收到此错误的原因是您没有选择Type。

        $res = mysql_query("SELECT DISTINCT `Specifically`,`Type` from `pet_table` WHERE `Type`='cat' ORDER BY `Specifically` ASC");
        
        while($row = mysql_fetch_assoc($res))
        {
            echo "The type is {$row['Type']} and it is specifically a {$row['Specifically']}
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-07
          • 2013-09-17
          • 1970-01-01
          • 2019-05-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多