0

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

非常感谢

4

3 回答 3

-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;
于 2013-01-27T16:20:11.960 回答
-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 
于 2013-01-27T16:20:28.063 回答
-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;
于 2013-01-27T16:36:13.013 回答