簡體   English   中英

MySQL雙左聯接,條件OR和組

[英]MySQL double left join, condition OR and group

我有一些問題。 我嘗試統計所有類別和子類別中的文章。

我使用以下查詢:

SELECT 
    cat.*, COUNT(art.id) AS total
FROM
    article_categories cat
        LEFT JOIN
    article_categories c2 ON (c2.category_parent = cat.category_id)
        LEFT JOIN
    articles art ON (art.cid = cat.category_id
        OR art.cid = c2.category_id)
WHERE
    cat.category_parent = 0 AND art.st = 1
        AND IF(art.cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22),
        TO_DAYS(CURDATE()) - TO_DAYS(art.date_edit) < 120,
        art.cid)
GROUP BY IF(c2.category_parent > 0,
    c2.category_parent,
    cat.category_id)
ORDER BY cat.category_order ASC

但對於某些類別,總計= 36355

當我使用此查詢時:

SELECT 
    *
FROM
    `articles`
WHERE
    st = 1
        AND cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22)
        AND IF(cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22),
        TO_DAYS(CURDATE()) - TO_DAYS(date_edit) < 120,
        cid)

總計= 7730

我究竟做錯了什么?

我的桌子:

articles:
- id
- cid
- title
- date_add
- date_edit
- st

article_categories
- category_id
- category_name
- category_order
- category_parent

感謝幫助

[編輯]

$sql1 = "SELECT cat.*, COUNT(art.id) AS total FROM article_categories cat LEFT JOIN articles art ON (art.cid = cat.category_id) WHERE cat.category_parent = 0 AND IF(art.cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22), TO_DAYS(CURDATE()) - TO_DAYS(art.date_edit) < 120, art.cid) GROUP BY art.cid";

$category = array();
foreach ($row as $cat) {
    $total = $cat['total'];
    $sql2 = "SELECT cat.*, COUNT(art.id) AS total FROM article_categories cat LEFT JOIN articles art ON (art.cid = cat.category_id) WHERE cat.category_parent = ".$cat['category_id']." AND IF(art.cid IN (2 , 4, 16, 17, 18, 19, 20, 21, 22), TO_DAYS(CURDATE()) - TO_DAYS(art.date_edit) < 120, art.cid) GROUP BY art.cid";
    foreach ($row2 as $cat2) {
        $total += $cat2['total'];
    }
    $category[] = array('category_id'=> $cat['category_id'], 'total' => $total);
}

我創建了另一個表:article_categories_rel。

article_categories_rel
- child_id
- parent_id

我自己的新查詢:

SELECT
    cat.*,
    COUNT(art.id) as ilosc
FROM
    article_categories cat
LEFT JOIN
    article_categories_rel acr
    ON
        (cat.category_id=acr.parent_id)
LEFT JOIN
    articles art
    ON (
        art.cid = acr.child_id AND
        art.st=1 AND
        if(art.cid in(2,4,16,17,18,19,20,21,22),
        TO_DAYS( curdate( ) ) - TO_DAYS( art.date_edit )<120,
        art.cid)
    )
WHERE
    cat.category_parent=0
GROUP BY
    cat.category_id
ORDER BY
    cat.category_order ASC;

它有效;)

暫無
暫無

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

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