2009-08-17 17 views
1

如何在一個標籤已知時選擇question_idtagSQL:獲取已知問題的所有標籤

我正在構建一個標籤搜索,它通過一個標籤搜索問題,以便結果顯示問題及其標籤,包括搜索中使用的問題。

我使用與this question相同的表格。 他們

questions   |  tags 
-------------------|----------------- 
    question_id  |  tag 
    title   |  question_id 
    was_sent_at_time | 

查詢

SELECT question_id, tag 
    FROM tags 
    WHERE question_id IN 
    ( 
     SELECT question_id 
     FROM questions 
     ORDER BY was_sent_at_time 
     DESC LIMIT 50 
    ) 
    AND tag = $1;   // Problem here 

與此查詢的問題是,它並不顯示分配的問題其他標籤。 如果存在給定標籤,可以獲取question_id和標籤。

+0

謝謝你的回答! – 2009-08-17 20:35:38

回答

1
SELECT TOP 50 q.question_id, q.title, t.tag 
    FROM tags t 
    INNER JOIN questions q 
    ON t.question_id = q.question_id 
    WHERE q.question_id IN 
    ( 
     SELECT tin.question_id 
     FROM tags tin 
     WHERE tin.tag = $1 
    ) 
    ORDER BY q.was_sent_at_time DESC 

這會回答你的問題(如果我理解正確),但我認爲你會有太多重複的數據 - 你不是真的想爲每個標籤重複問題標題。所以,你應該打破它分爲2個的結果集:

SELECT TOP 50 q.question_id, q.title 
    FROM questions q 
    WHERE q.question_id IN 
    ( 
     SELECT tin.question_id 
     FROM tags tin 
     WHERE tin.tag = $1 
    ) 
    ORDER BY q.was_sent_at_time DESC 

和:

SELECT t.question_id, t.tag 
    FROM tags t 
    WHERE t.question_id IN 
    ( 
     /* 
     SAME SQL AS ABOVE WITH SELECT q.question_id, 
     OR SELECT FROM A TEMP TABLE THAT ABOVE WAS SAVED TO 
     */ 
    ) 
    ORDER BY t.question_id 

然後,當你建立自己的網頁或什麼的,你把他們聚在一起。

+0

**您在'SELECT'中查詢「TOP 50」的目的是什麼? – 2009-08-17 19:45:04

+0

它與sql server中的限制50相同。 – 2009-08-17 19:49:32

+1

我很確定這是相反的:limit是pgsql,top是mssql。 – Kev 2009-08-17 19:55:25

1

你應該可以在數據庫中完成這項工作。你不想'在應用程序層中做到這一點。

 
ID | Questions 
---|---------- 
1 | How much does a duck weigh? 
2 | What is your gender? 
3 | What is your ducks gender? 

Question ID | Tags 
------------|------- 
1   | Duck 
2   | Gender 
3   | Duck 
4   | Gender 

注意標籤名是由於複製到您的架構設計

因此,要獲得大約鴨(問題1和3),你需要做的所有問題

SELECT * from tags t 
INNER JOIN questions q on t.question_id = q.question_id 
WHERE 
t.tag = 'Duck' 
ORDER BY was_sent_at_time 
DESC LIMIT 50 
+0

您的重複代碼令我困惑。現在很清楚。 – 2009-08-17 19:47:45