Mysql 如何从2列中检索每个数字组合

Mysql 如何从2列中检索每个数字组合,mysql,Mysql,我试图找到一种方法,从表中的两列检索每个值的组合,其中每个组合匹配第三列中的一个值 假设表格的一部分如下所示: products_id options_id options_values_id 1487 2 1 1487 2 61 1487 3 60 1487 5 52 使用produc

我试图找到一种方法,从表中的两列检索每个值的组合,其中每个组合匹配第三列中的一个值

假设表格的一部分如下所示:

products_id     options_id     options_values_id
1487            2              1
1487            2              61
1487            3              60 
1487            5              52
使用products_id 1487时,我希望的输出是以下两个字符串:

2-1, 3-60, 5-52
2-61, 3-60, 5-52
我的印象是,这些字符串需要递归地组装,但我在尝试这种方式时遇到了麻烦,因为不是每个产品都有相同的选项或相同数量的选项

编辑后添加:我尝试了下面几种解决方案的变体,但都无效。我想我应该更具描述性


我试图让它检索唯一选项的每个组合及其对应的选项值(换句话说,不是这两列中的每个可能的数字组合)。选项值表示产品选项,如“颜色”和“大小”,选项值表示这些选项的选择,如“红”或“小”因此,我试图为给定的产品id提供所有可能的选项组合。在上面的示例中,该项目有两种可能的选项组合--“2-1,3-60,5-52”和“2-61,3-60,5-52”

针对每个不同的选项将表自身连接起来。

先选择以检索选项数

$tables = array();
$rs = mysql_query(
  'SELECT DISTINCT options_id FROM table WHERE products_id = '.$id);
while ($row = mysql_fetch_row($rs)) {
  $tables[$row['options_id']] =
    'SELECT options_values_id FROM table WHERE products_id = '.$id.
    ' AND options_id = '.$row['options_id'];
}
mysql_free_result($rs);
然后,对于每个选项,将其作为单独的表加入到查询中。不要包含任何比较值的连接子句,只需将每个记录与其他记录连接起来即可

$sql = 'SELECT ';
$count = 0;
foreach ($tables AS $id => $query) {
  if ($count++) $sql .= ', ;
  $sql .= 'table_'.$id.'.options_values_id AS value_'.$id;
}
$sql .= ' FROM ';
$count = 0;
foreach ($tables AS $id => $query) {
  if ($count++) $sql .= ', ';
  $sql .= '('.$query.') AS table_'.$id;
}

最后,执行该查询。每行将包含每个
选项\u id
的一列。每个值的唯一组合将有一行。

或者对于混合的php/sql方法,请尝试使用该sql查询:

SELECT products_id, options_id, options_values_id WHERE products_id = '$var_with_product_id';
将结果提取到数组中,例如$results:

$pairs = array();
foreach($results as $result) {
    // build array with pairs (array_push to avoid overwriting)
    array_push($pairs, array( $result['options_id'] => $result['options_values_id'];
}
// a bit extra complication, as array_push adds e.g. [0] => array( options_id => options_values_id ) :)
$pairs = array_values($pairs);
// check for double options_id
$found_double_options_id = false;
do {
    // check for duplicates... use a lot of array functions
} while (count($pairs) && $found_double_options_id);
“每种组合”是指:


把桌子连在一起就行了
SELECT DISTINCT e1.options_id, e2.options_values_id
  FROM Entity e1, Entity e2
  WHERE e1.products_id = 1487 AND e2.products_id=1487