ORDER BY来自一个查询中的两个表的结果

时间:2013-12-25 01:04:33

标签: php mysql

我在我的网站上进行实时搜索功能

$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,但这不起作用......

3 个答案:

答案 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");

查询的作用:

  1. 根据$ search
  2. 搜索关键字中的字词和金额
  3. 根据$ search
  4. 搜索来自popular_search的字词和金额
  5. 联盟上面的查询和别名作为标签
  6. 按my_field
  7. 分组标签
  8. 按SUM(金额)DESC订购
  9. 限制10返回前10条记录
  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。