我有一个20行的表,例如:
2,3,5,6,8,22
2,3,5,6,8,22,44,55
etc.
Run Code Online (Sandbox Code Playgroud)
如何从mysql表行中仅选择唯一的数字,而不是重复的,因此结果如下:
2,3,5,6,8,22,44,55
Run Code Online (Sandbox Code Playgroud)
表定义:
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');
Run Code Online (Sandbox Code Playgroud)
这是我的尝试:
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 '';
}
}
Run Code Online (Sandbox Code Playgroud)
因为这只是一个领域,你可以这样做:
$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);
Run Code Online (Sandbox Code Playgroud)
但是您应该考虑更改数据库设计,看起来您的数据没有规范化.
参考:explode(),array_merge(),array_unique()
要知道你想要做什么样的查询,更好的表格布局将是:
| id | facility |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
...
| 3 | 1 |
| 3 | 7 |
| 3 | 9 |
...
Run Code Online (Sandbox Code Playgroud)
并且然后,你可能只是这样做:
SELECT DISTINCT facility FROM ...
Run Code Online (Sandbox Code Playgroud)