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 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题