通过筛选查询排序mysql查询

时间:2010-03-12 22:19:19

标签: mysql join filter

我有两个mysql查询:

$sql = "SELECT * FROM content WHERE threadName LIKE '%$filter%' ORDER BY lastUpdated desc";

$sql = "SELECT * FROM content ORDER BY lastUpdated desc";

最终结果是从特定表'content'返回所有行,但是那些匹配顶部变量$ filter的那些行。是否有单个查询可以组合这两个或我应该使用JOIN?

............仍然没有运气。这就是我目前所拥有的:

$sql = "SELECT * FROM content WHERE threadName LIKE '%$filter%' ORDER BY lastUpdated desc UNION SELECT * FROM content WHERE threadName NOT LIKE '%$filter%' ORDER BY lastUpdated desc";

给出:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/andrew/public_html/PHP/threadDisplay.php  on line 20

虽然第一部分(UNION之前)在单独使用时有效。

2 个答案:

答案 0 :(得分:1)

如何使用CASE STATEMENT

这样的东西
SELECT  * 
FROM    content 
ORDER BY CASE 
            WHEN threadName LIKE '%$filter%' THEN 0
            ELSE 1
        END ASC,
        lastUpdated desc

答案 1 :(得分:1)

(SELECT *
FROM   content
WHERE  threadName LIKE '%$filter%')
UNION
(SELECT *
FROM   content
WHERE  threadName NOT LIKE '%$filter%')
ORDER BY lastUpdated desc

修改MySQL需要一些包围,并且需要在工会后执行订单,抱歉忘记了。