如何从MySQL表行中选择唯一

如何从MySQL表行中选择唯一

我有一张20行的桌子,一行有例如:

2,3,5,6,8,22
2,3,5,6,8,22,44,55
etc.

如何从mysql表行中选择唯一的数字,而不是重复的,因此结果是:
2,3,5,6,8,22,44,55

表定义:
CREATE TABLE IF NOT EXISTS `test` (

  `id` int(11) NOT NULL auto_increment,

  `active` tinyint(1) NOT NULL default '1',

  `facilities` varchar(50) NOT NULL,

  PRIMARY KEY  (`id`)

) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

INSERT INTO `test` (`id`, `active`, `facilities`) VALUES

(1, 1, '1,3,5,6,7,8'),

(2, 1, '2,3,4,5,8,9'),

(3, 1, '4,5,6,7,9,10');

以下是我的尝试:
SELECT DISTINCT facilities FROM test WHERE active='1'

$dbgeneral= explode(',', $row['facilities']);


$facilities = array(

"Air Conditioning" => "2",

"Balcony" => "4");

foreach ($facilities as $facilities=> $v) {

     if(in_array($v,$dbgeneral)) {

echo '';

}
}

最佳答案

由于这只是一个字段,您可以执行以下操作:

$result = mysql_query('SELECT facilities FROM table');

$facilities = array();

while(($row = mysql_fetch_array($result))) {
    $facilities = array_merge($facilities , explode(',', $row[0]));
}

$facilities = array_unique($facilities);

但是您应该考虑更改数据库设计,看起来您的数据没有标准化。
参考文献:explode()array_merge()array_unique()
根据要执行的查询类型,更好的表布局应该是:
 | id  | facility |
 |  2  | 1        |
 |  2  | 2        |
 |  2  | 3        |
 ...
 |  3  | 1        |
 |  3  | 7        |
 |  3  | 9        |
 ...

然后你就可以:
SELECT DISTINCT facility FROM ...

09-19 01:03