簡體   English   中英

依靠列過濾器大於

[英]count on column filter by where greater than

任何人都可以讓我知道下面的正確MySQL語法

SELECT ta.id, 
       ta.raw,
       ta.title, 
       ta.hits as tag_hits, 
       it.hits as image_tag_hits,

       (SELECT count(*) 
        FROM image_tag 
        WHERE image_tag.tag_title_id = ta.id) as tag_count
FROM tag_title ta
INNER JOIN image_tag it ON ta.id = it.tag_title_id
INNER JOIN image im ON it.image_id = im.id
WHERE im.id = '12975' AND tag_count >0;

非常感謝

試着用having

SELECT ta.id, ta.raw,ta.title, ta.hits as tag_hits, it.hits as image_tag_hits,
(SELECT count(*) from image_tag where image_tag.tag_title_id = ta.id) as tag_count
FROM tag_title ta
INNER JOIN image_tag it ON ta.id = it.tag_title_id
INNER JOIN image im ON it.image_id = im.id
WHERE im.id = '12975' 
group by ta.id, ta.raw, ta.title, ta.hits, it.hits
having tag_count >0;

如果您想保留where ,也可以這樣做:

    SELECT * FROM (
    SELECT ta.id, ta.raw,ta.title, ta.hits as tag_hits, it.hits as image_tag_hits,
    (SELECT count(*) from image_tag where image_tag.tag_title_id = ta.id) as tag_count
    FROM tag_title ta
    INNER JOIN image_tag it ON ta.id = it.tag_title_id
    INNER JOIN image im ON it.image_id = im.id
    WHERE im.id = '12975' )X
   WHERE X.tag_count >0;

嘗試這個::

SELECT 
ta.id, 
ta.raw,
ta.title, 
ta.hits as tag_hits, 
it.hits as image_tag_hits, 
count(ta.id) as tag_count 
FROM tag_title ta 
INNER JOIN image_tag it ON ta.id = it.tag_title_id 
INNER JOIN image im ON it.image_id = im.id 
INNER JOIN image_tag ON image_tag.tag_title_id = ta.id
WHERE im.id = '12975'
GROUP BY ta.id having tag_count >0 

我不知道您的數據庫外觀如何,但我相信您正在尋找該解決方案:

SELECT
    ta.id, 
    ta.raw,
    ta.title, 
    ta.hits as tag_hits, 
    it.hits as image_tag_hits,
    COUNT(*) as tag_count
FROM
    image_tag it
LEFT JOIN
    tag_title ta ON
    ta.id = it.tag_title_ID
LEFT JOIN
    image im ON it.image_id = im.id
WHERE
    im.id = 12975
    # not need for tag_count=0, because if there is no image_count there will be no row :)
GROUP BY
    it.tag_title_id

並且有您的查詢(固定)

SELECT
    ta.id, 
    ta.raw,
    ta.title, 
    ta.hits as tag_hits, 
    it.hits as image_tag_hits,
    tcount.tag_count
FROM
    tag_title ta
LEFT JOIN
    ( 
    SELECT 
        tag_title_id,
        count(*) as tag_count
    FROM 
        image_tag 
    GROUP BY
        tag_title_id
    ) tcount ON tcount.tag_title_id = ta.id
INNER JOIN image_tag it ON ta.id = it.tag_title_id
INNER JOIN image im ON it.image_id = im.id
WHERE im.id = '12975' AND tcount.tag_count >0;

暫無
暫無

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

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