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

时间:2016-02-04 20:43:51

标签: php mysql sql select pdo

我在帖子表(示例)中提供了以下结构:

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 的帖子ft。像这样:

foreach

我可以做"过滤"具有foreach($query as $ex) { switch($ex["ft"]) { ... } } 的{​​{1}},例如:

query

但是,我的第一个LIMIT 7需要querysft个问题querys需要从所有中选择最后4个结果讯息。

如何执行此操作而无需执行倍数div

修改

我需要在一个ft = 1中显示最近7个帖子(一般),在另一个div中显示最后4个包含图片的帖子(ft = 2),最后4个帖子提及( div)另一个ft = 3中的div以及另一个ng-true-value中带有主题标签(ng-false-value)的最后4个帖子。

1 个答案:

答案 0 :(得分: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