如果它们不在前3中,请选择5行

时间:2014-02-14 14:09:18

标签: mysql

我想从表格中选择5篇不是最新的文章。

以下是我如何从名为article的表中获得5篇文章:

SELECT * FROM article WHERE FOREIGN_ID_MENU = '".$id."' AND active = '1' ORDER BY date_created DESC LIMIT 0, 5;

我如何从同一张表中获得前3篇文章:

SELECT * FROM article WHERE active = '1' ORDER BY date_created DESC LIMIT 0, 3;

如何组合这些查询以选择5篇不是最新的文章?我是用PHP做的。

3 个答案:

答案 0 :(得分:1)

您可以使用UNION并使用大括号查询以使用每个查询的限制

(SELECT * FROM article WHERE active = '1' 
AND FOREIGN_ID_MENU != '".$id."'
ORDER BY date_created DESC LIMIT 0, 3)
UNION
(SELECT * FROM article WHERE 
FOREIGN_ID_MENU = '".$id."' AND active = '1' 
ORDER BY date_created DESC LIMIT 0, 5)
来自评论的

编辑

SELECT a.* FROM article a WHERE 
a.FOREIGN_ID_MENU = '".$id."' AND a.active = '1'
AND NOT EXISTS 
(SELECT 1 FROM article aa WHERE aa.active = '1' 
AND aa.id =a.id
ORDER BY aa.date_created DESC LIMIT 0, 3) 
ORDER BY a.date_created DESC LIMIT 0, 5

答案 1 :(得分:1)

如果每篇文章都有ID,您可以尝试:

SELECT 
  * 
FROM
  article 
WHERE FOREIGN_ID_MENU = '".$id."' 
  AND active = '1' 
  AND ID NOT IN 
  (SELECT 
    ID 
  FROM
    article 
  WHERE active = '1' 
  ORDER BY date_created DESC 
  LIMIT 0, 3) 
ORDER BY date_created DESC 
LIMIT 0, 5 ;

答案 2 :(得分:1)

我想要的是这个:

SELECT * FROM article WHERE
FOREIGN_ID_MENU = '".$id."' AND active = '1' AND
date_created < (SELECT date_created FROM article ORDER BY date_created DESC LIMIT 3,1)
ORDER BY date_created DESC LIMIT 0, 5"