问题
Say I have a table that has a column which goes:
Column B
apple
apple
apple
orange
apple
orange
orange
grapes
grapes
mango
mango
orange
And I want to query it in such a way that I get a list like so:
apple orange grapes mango
How do I do this in PHP SQL? Much thanks.
回答1:
Suppose your table is called 'Fruit' and this column is called 'B'. Here's how you would do it:
SELECT DISTINCT B FROM Fruit;
The 'DISTINCT' keyword will get you all unique results. That's the SQL part. In PHP, you write the query like this:
// Perform Query
$query = 'SELECT DISTINCT B FROM Fruit';
$result = mysql_query($query);
// Get result
while ($row = mysql_fetch_array($result)) {
echo $row['B'];
}
回答2:
Where do you want to do the actual filtering? SQL or PHP?
For SQL:
SELECT DISTINCT foo FROM table;
#or#
SELECT foo FROM table GROUP BY foo;
For PHP:
$foo = array('a','a','b','b','c');
$foo_filtered = array_unique($foo);
来源:https://stackoverflow.com/questions/1771777/how-to-make-a-list-of-unique-items-from-a-column-w-repeats-in-php-sql