tags:

views:

51

answers:

3

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 '';

}
}
+1  A: 

Use King's answer, he nailed it better than I would have anyways.

Althane
Thank you Althane.
Stipe
I didn't even think about table normalization when he posted (I assumed it was normalized...). I feel like I should have failed my database class now. =)
Althane
A: 

--removed-- since it was wrong/ didn't answer the question (based on the extra data provided). Felix Kling's answer is much better.

Doon
I cannot see how `DISTINCT` should help here... can you explain? It will return every row.
Felix Kling
well when I answered, I didn't have the rest of the DDL/Tables stuff from his answer above (due to the edits). in my table, yes it will return every row, but was assuming the other 20 records might have contained duplicates. but reading my answer it is wrong.. I'll edit..
Doon
@Doon: Ah ok.... now I understand how you understood the question ;)
Felix Kling
+5  A: 

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 ...
Felix Kling
Thank Felix, it works great! Now I can easily select for example FIND_IN_SET(2, facilities) OR FIND_IN_SET(6, facilities)
Stipe