2011-05-13 64 views
1

打擾一下,我沒有用英文提出一個明確的問題。php mysql查詢出所有的單詞,但不重複

我需要一些像這樣的mysql查詢:通過兩個表查詢所有項目名稱,UNION,但不重複。

這裏是我的表結構:

表:cxt_20110105

item   | ... many columns, but does not affect query, because I just need item. 
art   | 
collectibles | 
furniture | 
books  | 
arts   | 
books  | 
... many lines... 

表:cxt_20110106

item   | ... many columns, the columns structure is as well as table: cxt_20110105. 
art   | 
tickets  | 
cars   | 
furniture | 
tickets  | 
cars   | 
... many lines... 

所以

mysql_query(//how to write in here?) 
while ($row = mysql_fetch_array($result)) 
{ 
    //the result should be: art, collectibles, furniture, books, tickets, cars(every word, but not repeat) ; 
} 

感謝。

回答

2

UNION將爲您刪除重複項。

SELECT item FROM cxt_20110105 
UNION 
SELECT item FROM cxt_20110106 
3
SELECT item FROM cxt_20110105 

UNION DISTINCT <---the important bit. 

SELECT item FROM cxt_20110106 
+0

從[mysql文檔](http://dev.mysql.com/doc/refman/5.0/en/union.html):「UNION的默認行爲是重複的行從結果中刪除。可選的DISTINCT關鍵字除默認外沒有任何作用,因爲它還指定重複行刪除。「 – 2011-05-13 21:01:22

+0

我更喜歡寫明確的查詢,以明確發生了什麼。默認值是好的,但看到這樣拼寫出來就會讓其他人更清楚。 – 2011-05-13 21:06:46

+0

正確,DISTINCT沒有用。答案很簡單。我沒有很好地學習基礎知識。謝謝。 – cj333 2011-05-13 21:07:37

0

隨意刪除這個帖子....我誤解了什麼,他問

echo mysql_field_name ($row , 0); //art 

,你可以把它貼在一個循環和退出失敗(沒有更多的條目)或走的$長度排

$n = count($row); 
$i=0; 
while ($i<$n) { 
    echo mysql_field_name ($row , $i); 
    $i++; 
} 

注,由mysql_fetch_array返回的數組同時返回一個數字和文本索引,$ N可能是2個你什麼甲腎上腺素ed ... so $ n = int(count($ row)/ 2)

看起來我可能誤解了這個問題,雖然 - 我在想他是想在中間輸出字段名。然後再說一遍,在一個循環內本身就沒有意義。我的歉意