在多行和多列上使用DISTINCT

时间:2014-11-17 14:05:30

标签: php mysql

这是我的网址:link

我使用了以下代码:

<?php include "config.php";

//select a database to work with
$selected = mysql_select_db("projecten_test",$dbhandle) 
or die("Could not select examples");

// Get specific data from the "products" table
$result = mysql_query("SELECT DISTINCT cat1,cat2,cat3,cat4 FROM products") 
or die(mysql_error());  ?>

<?php



echo "<br /><table border='1'>";
echo "<tr> <th>cat1</th><th>cat2</th><th>cat3</th><th>cat4</th></tr>";

// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array($result)) {
// Print out the contents of each row into a table

echo "<tr><td>"; 
echo "<a href=\"#\">".$row['cat1']."</a>";
echo "</td><td>"; 
echo "<a href=\"#\">".$row['cat2']."</a>";
echo "</td><td>"; 
echo "<a href=\"#\">".$row['cat3']."</a>";
echo "</td><td>"; 
echo "<a href=\"#\">".$row['cat4']."</a>";
echo "</td></tr>"; 

} 

echo "</table>";
?>

我使用了DISTINCT,因为我不想在这些列中看到重复的值。

就我而言,我希望看到:

cat1列显示一个“旅行”和一个“荷兰” cat2栏显示一个“名人”和一个“水”

等......

我尝试过使用union和concat_group但是我无法正常工作。它现在显示的方式(在此表中)是必须的 - 我必须能够将每个猫行(或者稍后可能是div)移动到另一个地方。

非常感谢.. :))

1 个答案:

答案 0 :(得分:2)

很抱歉你的评论中的长谈话大声笑。但是,您获得的是每行中所有值的唯一组合。如果你想删除它,那么你将不得不做多次选择

示例案例

create table t
(id int, 
 name varchar(55), 
 cat1  varchar(55), 
 cat2 varchar(55), 
 cat3 varchar(55), 
 cat4 varchar(55));  
INSERT INTO t values
(1, 'test', 'a', 'b', 'c', 'd'), 
(2, 'test1', 'v', 'f', 'z', 'o'), 
(3, 'test', 'q', 'f', 'z', 'o');

您需要从每个列中选择一个不同的值并像这样连接每个列

SELECT COALESCE(t.cat1, '') as cat1, 
       COALESCE(t1.cat2, '') as cat2, 
       COALESCE(t2.cat3, '') as cat3, 
       COALESCE(t3.cat4, '') as cat4 
FROM
(   SELECT distinct cat1, @a := @a + 1 as ID_A 
    FROM t
    CROSS JOIN (SELECT @a := 0) UDV_A
    GROUP BY cat1
)t
LEFT JOIN
(   SELECT distinct cat2, @b := @b + 1 as ID_B
    FROM t
    CROSS JOIN (SELECT @b := 0) UDV_B
    GROUP BY cat2
) t1 ON t1.ID_B = t.ID_A
LEFT JOIN
(   SELECT distinct cat3, @c := @c + 1 as ID_C 
    FROM t
    CROSS JOIN (SELECT @c := 0) UDV_C
    GROUP BY cat3
) t2 ON t2.ID_C = t.ID_A
LEFT JOIN
(   SELECT distinct cat4, @d := @d + 1 as ID_D 
    FROM t
    CROSS JOIN (SELECT @d := 0) UDV_D
    GROUP BY cat4
) t3 ON t3.ID_D = t.ID_A
ORDER BY cat1 <> '' DESC, cat2 <> '' DESC, cat3 <> '' DESC, cat4 <> '' DESC;

FIDDLE DEMO

注意:

FROM()中的第一个子选择必须是具有最多不同值的列,否则此查询将失败。