我有两个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之前)在单独使用时有效。
答案 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需要一些包围,并且需要在工会后执行订单,抱歉忘记了。