简体   繁体   English

MySQL / PHP从多个列中仅选择唯一值,然后将它们放入单独的数组中

[英]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. 我试图使用PHP和MySQL从表中的多个列中选择唯一值(但不是表中的所有列),并将所有选定的唯一值都放在自己的数组中。 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. 下面的代码将$ make_array中所有列的所有唯一值放入,然后将空值放入所有其他数组中。

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语句,则可以:

$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'];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM