我有一个有 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 ...
关于php - 如何从MySQL表行中选择唯一的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3417414/