开发者

MySQL/PHP Selecting only unique values from multiple columns and put them into seperate arrays

Using PHP and MySQL I'm trying to select unique values from multiple columns in a table (but not all the columns in the table) and put all the unique values from each column selected in its own array. The uniqueness of each columns values should be compared only to other values in the same column.

The code below puts all the unique values from all the columns in the $make_array then puts empty values in all the rest of the arrays.

How can I select only unique values from these columns and put each columns values in its own array?

$sql = "
    (SELECT make FROM items)
    UNION
    (SELECT model FROM items)
    UNION
    (SELECT year FROM items)
    UNION
    (SELECT month FROM 开发者_运维问答items)
    UNION
    (SELECT day FROM items)
    UNION
    (SELECT hour FROM items)";

$result = @mysql_query($sql, $con) or die(mysql_error());

while($row = mysql_fetch_array($result)) {

    $make = $row[make];
    $model = $row[model];
    $year = $row[year];
    $month = $row[month];
    $day = $row[day];
    $hour = $row[hour];

    $make_array[make][] = $make;
    $model_array[model][] = $model;
    $year_array[year][] = $year;
    $month_array[month][] = $month;
    $day_array[day][] = $day;
    $hour_array[hour][] = $hour;
}


If you want to keep it as one SQL statement, then you could:

$sql = "
    SELECT DISTINCT 'make' as descr,make as val FROM items
    UNION
    SELECT DISTINCT 'model' as descr,model as val FROM items
    UNION
    SELECT DISTINCT 'year' as descr,year as val FROM items
    UNION
    SELECT DISTINCT 'month' as descr,month as val FROM items
    UNION
    SELECT DISTINCT 'day' as descr,day as val FROM items
    UNION
    SELECT DISTINCT 'hour' as descr,hour as val FROM items";

$result = @mysql_query($sql, $con) or die(mysql_error());

while($row = mysql_fetch_array($result)) {
    $make_array[$row['descr']][]=$row['val'];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜