douyi8315 2016-02-04 20:43
浏览 29
已采纳

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

I've the following structure in the post table (example):

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

and I've the query:

SELECT id, id_author, content, date, ft FROM post where id_author = '$author' ORDER BY id DESC LIMIT 7

But, I need too, to select the posts with your respective ft with LIMIT 4. Like this:

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

I could to do the "filter" of ft with a foreach, for example:

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

But, my first query need to have LIMIT 7 and the querys realtives to ft need to select the last 4 results from all posts.

How to do this without having to do multiples querys?

EDIT:

I need to show the last 7 posts (general) in one div, the last 4 posts with images (ft = 1) in another div, the last 4 posts with mentions (ft = 2) in another div and the last 4 posts with hashtags (ft = 3) in another div.

  • 写回答

1条回答 默认 最新

  • dongwo1914 2016-02-04 21:10
    关注

    You could do this with the UNION operator.

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据