我如何加入这些查询?

时间:2010-04-08 16:36:54

标签: mysql join outer-join

query1:

SELECT category.id, category.name, category.level, category.description, category.cat1, category.cat2, category.cat3, category.cat4, category.pri_color, category.sec_color, category.last_report AS report_id FROM category, reports_category_layout WHERE category.id = reports_category_layout.catID AND reports_category_layout.site_code = 'las'

query2:

SELECT DISTINCT category.id, COUNT(forum.id) AS posts, SUM(forum.view) AS views FROM category, forum WHERE category.id = forum.catID AND forum.approved = 'yes' AND forum.site_code = 'las' GROUP BY category.id

query3:

SELECT forum.catID, forum.title, forum.paragraph, forum.created, users.alias, forum.userID FROM forum, users, forum_cache WHERE forum.catID = forum_cache.catID AND forum.id = forum_cache.last_report AND users.id = forum.userID AND forum.approved = 'yes'

基本上,我不确定正确加入这些语法的语法。我编写了一个简单地加入它们的查询,但是如果论坛缓存表包含未经批准的论坛ID,它将不会返回整行。

我真正需要的是将query1和query2保留在类别ID上,并将查询3保留在id = catID的外部联接。

1 个答案:

答案 0 :(得分:0)

query1:

SELECT category.id, category.name, category.level, category.description, category.cat1, category.cat2, category.cat3, category.cat4, category.pri_color, category.sec_color, category.last_report AS report_id 
FROM category c
LEFT OUTER JOIN reports_category_layout rcl on c.id = rcl.catID
    AND rcl.site_code = 'las'

query2:

SELECT DISTINCT category.id, COUNT(forum.id) AS posts, SUM(forum.view) AS views 
FROM category c
LEFT OUTER JOIN forum f on c.id = f.catID 
    AND f.approved = 'yes' 
    AND f.site_code = 'las' 
GROUP BY c.id

query3:

不确定你要求的是什么,但是对它进行了抨击:

SELECT forum.catID, forum.title, forum.paragraph, forum.created, users.alias, forum.userID 
FROM forum f
INNER JOIN users u on u.id = f.userID
LEFT OUTER JOIN forum_cache fc on f.catID = fc.catID 
    and f.id = fc.last_report 
WHERE f.approved = 'yes'