开发者

How to return a column value only once in MySQL

I need help with this. I have a database that displays product type titles.

My code so far is:

    $query = mysql_query("SELECT type FROM certs ORDER by type") or die("Could not execute query"); 


while($row = mysql_fetch_array($query) )
{

   $product .= "<h1>".$row["type"]."</h1>";
}

echo($product);

which returns

<h1>MR001</h1>
<h1>MR001<开发者_运维百科/h1>
<h1>MR002</h1>
<h1>MR003</h1>
<h1>MR003</h1>
<h1>MR004</h1>
<h1>MR004</h1>
<h1>MR004</h1>

etc., but I need it to only return the same value once?

Like

<h1>MR001</h1>
<h1>MR002</h1>
<h1>MR003</h1>
<h1>MR004</h1>

STUCK.COM HELP!!!


Use DISTINCT in the SQL Query.. Try this:

$query = mysql_query("SELECT DISTINCT type FROM certs ORDER by type") or die("Could not execute query");

while($row = mysql_fetch_array($query) ) 
{     
   $product .= "<h1>".$row["type"]."</h1>"; 
}  


Change your query to use DISTINCT, which will only return unique rows:

mysql_query("SELECT DISTINCT type FROM certs ORDER by type")

For ease of use, your entire corrected code will be as follows:

$query = mysql_query("SELECT DISTINCT type FROM certs ORDER by type") or die("Could not execute query");
while($row = mysql_fetch_array($query) )
{
    $product .= "<h1>".$row["type"]."</h1>";
}
echo($product);


It's better to do this with MySQL using DISTINCT

SELECT DISTINCT type FROM certs ORDER by type

Read more about using DISTINCT in MySQL.


I think you want to use SELECT DISTINCT type. . . .


Try DISTINCT:

"SELECT DISTINCT type FROM certs ORDER by type"


Take a look at GROUP BY and also the DISTINCT operators.

For your specific example:

$query = mysql_query("SELECT DISTINCT type FROM certs ORDER by type") or die("Could not execute query"); 


Use group by

SELECT type FROM certs GROUP BY type

( bit offtopic ) - it is better to have type definitions in separate table ( eg not in certs , but in own table ) - and linket thru foreign key ( eg. type_id instead of type - it will 1 for MR001, 2 for MR002 etc )

For listing of certs with type names use JOIN


You're looking for SELECT DISTINCT. You may want to view the full MySQL syntax for Select.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜