2013-03-12 118 views
1

我试图从'特定'中选择不同的名称,但只有col类型=特定的值。mysql从col1中选择不同的行WHERE col2 = x

比如我有

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>"); 
} 

我也想做类似的地方类型不是猫或狗或马... ECT

感谢

回答

1

你想GROUP BY

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

他需要'Type'列以及 – varnie 2013-03-12 17:54:43

+0

固定,谢谢修正 – fredrik 2013-03-12 17:56:33

2

该指数不存在,因为你不选择它。在您的SELECT声明中加入Type来解决它。

2

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

将您的查询改为。其次,如果你想要Type不是猫或狗或马,你可以使用NOT IN子句。

最后,请不要使用MySQL,因为它不会被维护,因此不推荐使用。考虑使用MySQLi或PDO。

0

你得到这个错误的原因是因为你没有选择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']} 
} 
相关问题