How to make a list of unique items from a column w/ repeats in PHP SQL

不问归期 提交于 2019-12-11 12:36:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!