我在我的网站上进行实时搜索功能
$result =
mysql_query("SELECT word as my_field FROM keywords
WHERE word LIKE ('" . $search . "%')
UNION
SELECT term as my_field FROM popular_search
WHERE term LIKE ('" . $search . "%') GROUP by my_field LIMIT 10");
我正在尝试从两个表中获取结果,因为我可以看到它工作正常,但在两个表中,关键字和 popular_search ,我有字段金额所以我需要按金额对上面的查询进行排序,这样我就可以获得相关且受欢迎的结果。我正在尝试使用ORDER量的DESC,但这不起作用......
答案 0 :(得分:1)
您需要在amount
列表中添加SELECT
列:
$result = mysql_query("SELECT word as type, amount
FROM keywords
WHERE word LIKE ('" . $search . "%')
UNION
SELECT term as type, amount
FROM popular_search
WHERE term LIKE ('" . $search . "%')
GROUP by type
ORDER BY amount DESC
LIMIT 10");
仅供参考,上面的GROUP BY
子句仅适用于popular_search
查询,而不适用于UNION
。如果您希望它同时适用于两者,则需要将UNION
放在子查询中,然后执行:SELECT <columns> FROM (<subquery>) x GROUP BY type
。您可能还想使用SUM(amount)
或MAX(amount)
。
答案 1 :(得分:1)
尝试此查询:
$result =
mysql_query("SELECT my_field, SUM(amount) sum_amount
FROM (
SELECT word as my_field, amount
FROM keywords
WHERE word LIKE ('{$search}%')
UNION
SELECT term as my_field, amount
FROM popular_search
WHERE term LIKE ('{$search}%')
) tab
GROUP BY my_field
ORDER BY SUM(amount) DESC
LIMIT 10");
查询的作用:
希望这有帮助。
答案 2 :(得分:0)
尝试从选择中进行选择:
SELECT * FROM (
SELECT amount, … FROM keywords
WHERE word LIKE CONCAT(:search, '%')
UNION SELECT amount, … FROM keywords
WHERE term LIKE CONCAT(:search, '%')
GROUP BY type LIMIT 10
) ORDER BY amount
我不确定这是否适用于MySQL。