2012-03-06 50 views
2

這裏是我的查詢如何把如果LIMIT MySQL的其他條件

$where_or = " 
       AND 
        content_status = 'Active' 
       AND 
        content_post_status = 'published' 
       AND 
        deleted = 0 
       AND 
        content_type = '$type' 
       ORDER BY content_created_at DESC "; 

     $select = "content_id, content_title, content_short_description, content_url, content_created_at"; 

     $query = $this->db->query(" 
       (
        SELECT $select 
        FROM tbl_content 
        WHERE 
        content_category_id = 54 
        $where_or 
        LIMIT 3 
       ) 
       UNION ALL 
       (
        SELECT $select 
        FROM tbl_content 
        WHERE 
        content_category_id = 55 
        $where_or 
        LIMIT 2 
       ) 
       UNION ALL 
       (
        SELECT $select 
        FROM tbl_content 
        WHERE 
        content_category_id = 56 
        $where_or 
        LIMIT 2 
       ) 
       UNION ALL 
       (
        SELECT $select 
        FROM tbl_content 
        WHERE 
        content_category_id = 57 
        $where_or 
        LIMIT 1 
       ) 
       UNION ALL 
       (
        SELECT $select 
        FROM tbl_content 
        WHERE 
        content_category_id = 58 
        $where_or 
        LIMIT 1 
       ) 
       UNION ALL 
       (
        SELECT $select 
        FROM tbl_content 
        WHERE 
        content_category_id = 60 
        $where_or 
        LIMIT 1 
       ) 
       UNION ALL 
       (
        SELECT $select 
        FROM tbl_content 
        WHERE 
        content_category_id = 61 
        $where_or 
        LIMIT 1 
       ) 
       UNION ALL 
       (
        SELECT $select 
        FROM tbl_content 
        WHERE 
        content_category_id = 118 
        $where_or 
        if content_type = 'article' 
        begin 
         LIMIT 10 
        end 
       ) 
     "); 

可以在最後UNION看到我想提出的限制。如果條件..但它給我的錯誤...我怎麼能這樣做...請幫助..

+2

那......沒有任何意義。 – Konerak 2012-03-06 06:13:53

+0

我解決了它與php ..感謝 – saba 2012-03-06 06:20:52

回答

1

你不能這樣做與MySQL,至少不是你想要的方式。如果你仔細想想這個:

if content_type = 'article' 
begin 
    LIMIT 10 
end 

沒有意義。 LIMIT應用於一個集合而不是單個記錄。如果你寫的是有效的SQL,並且你的數據包含content_type ='article'的真實內容和一些錯誤的內容。你期望會發生什麼?

+0

我甚至不想知道你爲什麼這樣做,很高興你找到了適合你的解決方案。 – 2012-03-06 15:29:09

0

我建議你排名記錄,然後添加WHERE條件篩選記錄content_category_id及其排名。在這種情況下,您將避免使用多個SELECT ... FROM查詢。

+0

我有兩個表tbl_cats和tbl_content ... tbl_content有cat_id ..我必須得到記錄的基礎上cat_id ...像cat_id = 1記錄限制將是3等...還有其他方式做這個但在我看來,最簡單的做法就是...... – saba 2012-03-06 09:05:57