依靠列筛选器大于的位数

时间:2013-01-27 16:17:58

标签: mysql join inner-join

任何人都可以让我知道下面正确的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;

非常感谢

3 个答案:

答案 0 :(得分:-1)

尝试使用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;

答案 1 :(得分:-1)

试试这个::

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 

答案 2 :(得分:-1)

我不知道您的数据库是怎样的,但我相信您正在寻找解决方案:

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;