2010-10-14 108 views
0

使用PHP和MySQL我試圖從表中的多列(但不是表中的所有列)中選擇唯一值,並將所有列在其自己的數組中選擇每個列的唯一值。每列值的唯一性應僅與同一列中的其他值進行比較。MySQL/PHP從多列中選擇唯一值並將它們放入單獨的數組中

以下代碼將所有列中的所有唯一值放在$ make_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; 
} 
+0

什麼用獨特的日子嗎?幾個小時? – 2010-10-14 18:14:18

+0

@Col彈片與問題無關。他們只是這個例子的樣本值。 – Mark 2010-10-14 18:16:57

+0

你知道,你的整個問題與常識沒什麼關係。我只是想弄清楚爲什麼你需要這種不尋常的東西。 – 2010-10-14 18:20:20

回答

2

如果你想保持它作爲一個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']; 
} 
+0

@Mark這將做你正在做的事情,雖然我不確定你想做什麼很有意義。您可能會將它們作爲單獨的查詢執行。 – 2010-10-14 18:25:58

+0

當然不會不同意這個@bemace,儘管從Mark的評論中也許這只是一個僞示例 - 也許這種方法對他的應用更有意義。 – Rudu 2010-10-14 18:29:36

相關問題