php - 从同一个表中选择不同的结果

标签 php mysql sql select pdo

我在 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

但是,我也需要选择带有您各自的ftLIMIT 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

我可以使用 foreachft 进行“过滤”,例如:

foreach($query as $ex) {
    switch($ex["ft"]) {
        ...
    }
}

但是,我的第一个查询需要有LIMIT 7,并且需要选择ft查询实数所有帖子的最后 4 个结果。

如何在不必执行多个查询的情况下执行此操作?

编辑:

我需要在一个 div 中显示最后 7 篇帖子(常规),在另一个 div< 中显示最后 4 篇带有图像的帖子 (ft = 1),最后 4 篇在另一个 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/

相关文章:

php - 提取特定捆绑产品订单

mysql - 每组最多选择 x 行

sql - 谁能解释一下数据库中的 "storing"和 "indexing"?

javascript - 如何防止 HTML 中的标签和脚本执行?

php - 上传没有临时名称的文件

php - 更新 MySql 字段(如果字段不为空,转到下一个)

mysql - 连接 3 个表 MySQL

php - PHP中的多重继承

php - 与 vb.net 和 php 数据同步

mysql - 如何检查 MySQL 查询是否正在使用覆盖索引?