【问题标题】:How to select unique arrays from MySQL table row?如何从 MySQL 表行中选择唯一数组?
【发布时间】:2010-08-05 17:26:40
【问题描述】:

我有一个有 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 '';

}
}

【问题讨论】:

  • 这个字段是用逗号分隔的数字吗?
  • 你能显示表格定义吗? SSince althane 的 distinct 答案可能是正确的,但是您的每个“行”是否仅包含 1 个字段?还是他们的多个领域?
  • 这是我的桌子:id 2 - 3 - 5 设施 1,2,3,4,5,8,9 - 1,7,9,11,13 - 4,5,6, 9,10
  • 我还没有理解这个概念 - 你能发布表格的 DDL 吗?

标签: php mysql arrays


【解决方案1】:

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

$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 ...

【讨论】:

  • 感谢 Felix,效果很好!现在我可以轻松选择例如 FIND_IN_SET(2, facility) 或 FIND_IN_SET(6, facility)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 2016-11-01
相关资源
最近更新 更多