我在帖子表中有以下结构(示例):
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
来帖子。像这样: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
我可以用
LIMIT 4
做ft
的“过滤器”,例如:foreach($query as $ex) {
switch($ex["ft"]) {
...
}
}
但是,我的第一个
foreach
需要具有query
,而LIMIT 7
的querys
实境需要从所有帖子中选择最后4个结果。怎么做而不必做倍数
ft
?编辑:
我需要在一个
querys
中显示最后7个帖子(常规),在另一个div
中显示带有图像(ft = 1
)的最后4个帖子,在另一个div
中显示带有提及(ft = 2
)的最后4个帖子最后4个帖子在另一个div
中带有标签(ft = 3
)。 最佳答案
您可以使用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/