简体   繁体   中英

MySQL double left join, condition OR and group

i have got some problem. I try count all articles in categories and subcategories.

I use this query:

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

but for some category total = 36355

when i use this query:

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)

total = 7730

What am I doing wrong?

My tables:

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

article_categories
- category_id
- category_name
- category_order
- category_parent

Thanks for help

[EDIT]

$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);
}

I created another table: article_categories_rel.

article_categories_rel
- child_id
- parent_id

My own new query:

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;

and it works ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM