我在 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
我有查询
:
SELECT id, id_author, content, date, ft FROM post where id_author = '$author' ORDER BY id DESC LIMIT 7
但是,我也需要选择
带有您各自的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"]) {
...
}
}
但是,我的第一个查询
需要有LIMIT 7
,并且需要选择ft
的查询
实数所有帖子的最后 4 个结果。
如何在不必执行多个查询
的情况下执行此操作?
编辑:
我需要在一个 div
中显示最后 7 篇帖子(常规),在另一个 div< 中显示最后 4 篇带有图像的帖子 (
,最后 4 篇在另一个 ft = 1
)div
中提及的帖子 (ft = 2
) 以及最后 4 篇带有话题标签的帖子 (ft = 3
) ) 在另一个 div
中。
最佳答案
您可以使用UNION
运算符来完成此操作。
SELECT
'General' AS post_type,
id,
id_author,
content,
date,
ft
FROM
Post
WHERE
id_author = '$author'
ORDER BY
id DESC
LIMIT 7
UNION ALL
SELECT
'Image' AS post_type,
id,
id_author,
content,
date,
ft
FROM
Post
WHERE
id_author = '$author' AND
ft = 1
ORDER BY
id DESC
LIMIT 4
UNION ALL
SELECT
'Mentions' AS post_type,
id,
id_author,
content,
date,
ft
FROM
Post
WHERE
id_author = '$author' AND
ft = 2
ORDER BY
id DESC
LIMIT 4
UNION ALL
SELECT
'Hashtags' AS post_type,
id,
id_author,
content,
date,
ft
FROM
Post
WHERE
id_author = '$author' AND
ft = 3
ORDER BY
id DESC
LIMIT 4
关于php - 从同一个表中选择不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35211239/