【发布时间】:2016-05-14 16:02:07
【问题描述】:
我在 post 表中具有以下结构(示例):
id | id_author | content | date | ft
1 | 1 | hi! | 2016 | 2
2 | 1 | hello! | 2016 | 3
3 | 1 | welcome | 2016 | 1
4 | 1 | test! | 2016 | 2
我有query:
SELECT id, id_author, content, date, ft FROM post where id_author = '$author' ORDER BY id DESC LIMIT 7
但是,我也需要select 与您各自的ft 和LIMIT 4 的帖子。像这样:
SELECT id, id_author, content, date, ft FROM post where id_author = '$author' and ft = 1 ORDER BY id DESC LIMIT 4
SELECT id, id_author, content, date, ft FROM post where id_author = '$author' and ft = 2 ORDER BY id DESC LIMIT 4
SELECT id, id_author, content, date, ft FROM post where id_author = '$author' and ft = 3 ORDER BY id DESC LIMIT 4
我可以用foreach 对ft 进行“过滤”,例如:
foreach($query as $ex) {
switch($ex["ft"]) {
...
}
}
但是,我的第一个query 需要有LIMIT 7 和querys 到ft 需要从所有 个帖子中选择最后4 个结果。
如何做到这一点而不必做多个querys?
编辑:
我需要在一个 div 中显示最后 7 个帖子(一般),在另一个 div 中显示最后 4 个带有图像的帖子 (ft = 1),在另一个 ft = 2 中显示最后 4 个带有提及的帖子 (ft = 2) div 和最后 4 个带有主题标签 (ft = 3) 的帖子在另一个 div 中。
【问题讨论】:
-
如果使用
IN子句会怎样?像这样:SELECT id, id_author, content, date, ft FROM post where id_author = '$author' and ft IN {1,2,3} ORDER BY id DESC LIMIT 4这是你想要的吗?告诉我。 -
请给出您的预期输出。
-
我编辑了我的问题
-
@Igor,我认为在这种情况下您可以从创建存储过程 (SP) 中受益。因为这不会给你你想要的东西:
SELECT id, id_author, content, date, ft FROM post where id_author = '$author' and ft IN {1,2,3} ORDER BY id DESC LIMIT 7因为如果ft=1返回 7 行,那么查询就完成了,忽略其余的。我建议你使用 SP。 -
是的,@pablo-rivas 如果我使用
IN结果将是LIMIT 7...