I have a table with 20 rows and one row have for example:
2,3,5,6,8,22
2,3,5,6,8,22,44,55
etc.
How can I select from mysql table rows only unique numbers, not duplicated so results are:
2,3,5,6,8,22,44,55
The table definition:
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');
Here is my attempt:
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 '';
}
}
As this is only one field, you could do something like:
$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);
But you should consider to change your database design, it looks like your data is not normalized.
Reference: explode()
, array_merge()
, array_unique()
Depening on what kind of queries you want to do, a better table layout would be:
| id | facility |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
...
| 3 | 1 |
| 3 | 7 |
| 3 | 9 |
...
and then you could just do:
SELECT DISTINCT facility FROM ...
用金的答案,他比我反而会更好。
--removed-- since it was wrong/ didn't answer the question (based on the extra data provided). Felix Kling's answer is much better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.