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 - 'order 子句'中的未知列 'rank'

4

2 回答 2

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会忽略选定的字段。它也可以阅读:

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

它的工作原理是一样的。

WHERE EXISTS-subquery 视为返回一个布尔值,除了那个布尔值之外什么都没有。

如果您希望从 table2 计算排名,则必须将 a 添加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

如果table2 中最多只有一个匹配行,则可以不使用该GROUP BY子句,只需进行直接连接

SELECT t1.data1, MATCH (...) AGAINST (...) AS rank
FROM table1 t1 
JOIN table2 t2 ON (MATCH (...) AGAINST (...))
ORDER BY rank DESC
于 2013-04-20T17:34:41.740 回答
0

在 SQL 语句中,您只能在主子from句中引用表/子查询中的列。您的子查询在where子句中。

您需要将其重写为join. 如果id在 table2 中是唯一的,这将起作用:

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
于 2013-04-20T17:55:28.000 回答