2013-04-20 84 views
1

繼我的查詢:訂單結果全文

SELECT data1 
FROM table1 t1 
WHERE EXISTS (
SELECT id, 
MATCH (
... 
) 
AGAINST (
... 
) AS rank 
FROM table2 t2 
WHERE MATCH (
... 
) 
AGAINST (
.... 
) 
) ORDER BY rank DESC 

的問題是,我不認識排名之外在哪裏,其實我看到以下消息:

#1054 - Unknown column 'rank' in 'order clause' 

感謝advace!

回答

0

在SQL語句中,只能引用主要的from子句中的表/子查詢中的列。你的子查詢是where子句。

你需要重寫這是一個join。如果id是表2中獨一無二的,這這將工作:

select data1 
from table1 t1 join 
    (SELECT id, MATCH (...) AGAINST (...) AS rank 
     FROM table2 t2 
     WHERE MATCH (...) AGAINST (....) 
    ) t2 
    on t1.id = t2.id 
order by t2.rank 

否則,你需要重複到:

select distinct data1, rank 
from table1 t1 join 
    (SELECT id, MATCH (...) AGAINST (...) AS rank 
     FROM table2 t2 
     WHERE MATCH (...) AGAINST (....) 
    ) t2 
    on t1.id = t2.id 
order by t2.rank 
+0

的例子是真的做得很好,你值得擁有最好的答案!所以謝謝你! – user2302554 2013-04-20 18:33:10

+0

TBH,我沒有看到這裏的子查詢的要求。我錯過了什麼嗎? – Hazzit 2013-04-20 18:41:08

0

您使用WHERE EXISTS和子查詢。

SELECT data1 FROM table1 t1 WHERE EXISTS (
    SELECT id, 
    MATCH (...) AGAINST (...) AS rank 
    FROM table2 t2 
    WHERE MATCH (...) AGAINST (...) 
) ORDER BY rank DESC 

在這方面中,MySQL ignores選定的字段。它可能也讀:

SELECT data1 FROM table1 t1 WHERE EXISTS (
    SELECT 42 
    FROM table2 t2 
    WHERE MATCH (...) AGAINST (...) 
) ORDER BY rank DESC 

而且它的工作一樣。

覺得WHERE EXISTS -subquery爲返回一個布爾值並沒有什麼但布爾的。

如果你想從表2中計算等級,你必須在你的主查詢中添加一個JOIN(可能還有GROUP BY子句)。

編輯:例

最可能的是,你不需要WHERE EXISTS條款。 (你的問題是太不具體確定,所以這裏的標準情況下)

SELECT t1.data1, MATCH (...) AGAINST (...) AS rank 
FROM table1 t1 
JOIN table2 t2 ON (MATCH (...) AGAINST (...)) 
GROUP BY t1.id, t1.data, rank 
ORDER BY rank DESC 

如果只有一個最大表2中一個匹配行的,你可以逃脫不GROUP BY條款,只是做了直接連接

SELECT t1.data1, MATCH (...) AGAINST (...) AS rank 
FROM table1 t1 
JOIN table2 t2 ON (MATCH (...) AGAINST (...)) 
ORDER BY rank DESC 
+0

你能舉個例子嗎? – user2302554 2013-04-20 17:40:09

+0

非常感謝你! – user2302554 2013-04-20 17:58:57