SQL元表帮助(mysql)

时间:2012-09-15 11:10:30

标签: mysql sql

我有3个表(“新闻”,“类别”和连接表“meta”)。我只是想过滤包含category_id的新闻,该新闻作为过滤器参数提供。我尝试了下面的查询(和类似的),但它从新闻表中返回所有新闻。

那么如何按meta_id (category_id)过滤这些新闻?

非常感谢!

// category table
category_id | category_name
---------------------------
55          | Sport
56          | Politics

// meta table
meta_id | meta_type | rel_id | rel_type
---------------------------------------
55      | category  | 78345  | news
56      | category  | 91278  | news

Notes:
rel_id (in meta table)  = id (in news table) // i don't need it in this case
meta_id (in meta table) = category_id (in category table)

SQL:

SELECT n.*
FROM `news` n
LEFT JOIN `metas` m ON m.meta_type='category'
    WHERE m.meta_id=55 AND n.status=1
GROUP BY n.id
ORDER BY n.id DESC
LIMIT 0,10

3 个答案:

答案 0 :(得分:1)

最重要的是将metasnews相关联。如果我正确阅读了您的问题,则链接字段为m.rel_id = n.id。以下示例查询应筛选类别55:

select  *
from    metas m
join    news n
on      m.rel_id = n.id
where   m.meta_type = 'category'
        and m.meta_id = 55
        and n.status = 1
order by
        n.id desc
limit   0, 10

N.B。不确定为什么您的查询中有group by。当然不需要过滤类别!

答案 1 :(得分:0)

您必须在ON子句中添加条件。

SELECT n.*
FROM `news` n
LEFT JOIN `metas` m ON m.meta_type='category' AND m.meta_id = n.category_id
    WHERE m.meta_id=55 AND n.status=1
GROUP BY n.id
ORDER BY n.id DESC
LIMIT 0,10

答案 2 :(得分:0)

SELECT n.*
FROM `news` n
LEFT outer JOIN `metas` m ON m.meta_id = n.category_id
    WHERE m.meta_id=55 AND n.status=1 and m.meta_type='category'
GROUP BY n.id
ORDER BY n.id DESC
LIMIT 0,10