【问题标题】:Select different results from the same table从同一个表中选择不同的结果
【发布时间】: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 与您各自的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"]) {
        ...
    }
}

但是,我的第一个query 需要有LIMIT 7querysft 需要从所有 个帖子中选择最后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...

标签: php mysql sql select pdo


【解决方案1】:

您可以使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2013-11-28
    • 2022-11-14
    • 1970-01-01
    • 2017-01-26
    • 2022-01-27
    相关资源
    最近更新 更多