2010-02-28 86 views
0

我是新來的MySQL,所以請你能幫助我。 我有2代表 「言」 與 「文」需要幫助與MySQL查詢

話有列:

  1. 同義詞

文本有列:

  1. 文本
  2. 單詞
  3. article_id

我需要獲得唯一的words.word和最大的唯一text.atricle_id字段。相同的article_id可以有不同的詞。例如

words 
word  synonyms 
----------------------- 
car  auto, vehicle 
water syn1, syn2  
bus  syn1, syn2 

text 
text   word  article_id 
--------------------------------------- 
any text  car   1 
any_text  water   1 
any_text  water   2 
any_text  car   2 
any_text  bus   1 
any_text  bus   3 

I need to get the result: 
car | 2 
water | 1 
bus | 3 

我有一個查詢,但它返回非唯一的article_id

SELECT words.word, text.article_id 
FROM `words` , `text` 
WHERE text.word = words.word 
GROUP BY words.word 
ORDER BY text.article_id DESC 

回答

0

也許這將做到這一點:

SELECT DISTINCT words.word, text.article_id 
FROM `words` , `text` 
WHERE text.word = words.word 
HAVING max(text.article_id) 
GROUP BY words.word 
ORDER BY text.article_id DESC 
1

這個查詢得到你的結果螞蟻:

SELECT words.word, max(text.article_id) as biggest_article_id 
FROM `words` , `text` 
WHERE text.word = words.word 
GROUP BY words.word 
ORDER BY text.article_id DESC 

結果:

word _ biggest_article_id 
bus | 3 
car | 2 
water | 2 

注1:水已經biggest_article_id = 2,而不是1 =你在問題中的狀態。

注2:ORDER BY text.article_id DESC不會按照您在問題中說明的順序給出結果。

+0

我需要最大的唯一article_id,所以這個查詢不適合我。 – bera 2010-02-28 14:30:46

+0

正如我理解你的問題,你想獲得與一個詞相關的最大的文章ID。我給你的查詢將做到這一點。你將文字分組,每一個人都會得到與給定單詞相關的最大文章ID。 – 2010-02-28 15:49:15

+0

有一件我不明白的事情:如果你想得到最大的文章ID,爲什麼在你顯示的結果中「水」這個詞有一個文章id = 1?在你的文本表中看到,你有一排'水',它有一個文章ID = 2,這是與'水'這個詞相關的最大的文章ID。 – 2010-02-28 15:53:00