簡體   English   中英

從同一張表中選擇不同的結果

[英]Select different results from the same table

我在帖子表中有以下結構(示例):

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

但是,我也需要selectft LIMIT 4相對應的ft的帖子。 像這樣:

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

我可以使用foreach來對ft進行“過濾”,例如:

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

但是,我的第一個query需要有LIMIT 7 ,對ftquerys需要從所有帖子中選擇最后4個結果。

如何執行此操作而不必執行多次querys

編輯

我需要顯示的最后7個(一般)在一個div ,最后4帖與圖像( ft = 1在另一個) div ,最后4帖與提及( ft = 2 )在另一個div和最后4個帖與在另一個div主題標簽( ft = 3 )。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM