2016-02-04 45 views
0

選擇不同的結果,我在表結構如下(舉例):從同一個表

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 

我可以做的ft 「過濾器」 與foreach,例如:

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

但是,我的第一個query需要有LIMIT 7querys realtives到ft需要從中選擇最後4個結果全部的帖子。

如何做到這一點,而不必做多倍querys

編輯

我需要顯示在過去的7個(一般)在一個div,最後4個帶有圖片的帖子(ft = 1)在另一個div,最後4個員額,在提到(ft = 2)另一個div和最後4個帶有#標籤的帖子(ft = 3)在另一個div

+1

如果使用'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'這就是你想要的嗎?讓我知道。 –

+2

請給出您的預期輸出。 –

+1

數據庫引擎=? – trincot

回答

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