过滤mysql连接表中的部分数据

时间:2015-03-23 08:33:04

标签: mysql sql filtering

这是我的初始mysql代码,它显示了我需要的东西:

    SELECT (
    CASE 
       WHEN (c.`norm_id` = 71) THEN 71
       ELSE c.parent_id
    END) AS parent, 
    SUM(d.number) AS parent_sum,
    COUNT(DISTINCT(c.norm_id)) AS child_cnt
FROM un_catalog AS c
    LEFT JOIN un_data AS d ON (c.norm_id =  d.type2_norm_id)
    LEFT JOIN exp_weblog_titles AS wt USING (entry_id)
WHERE (c.parent_id != '') AND (c.`type_id` = 2) OR (c.norm_id = 71) 
GROUP BY parent
ORDER BY parent ASC;

Here's what it shows

现在我添加一个过滤器:

 SELECT (
    CASE 
       WHEN (c.`norm_id` = 71) THEN 71
       ELSE c.parent_id
    END) AS parent, 
    SUM(d.number) AS parent_sum,
    COUNT(DISTINCT(c.norm_id)) AS child_cnt
FROM un_catalog AS c
    LEFT JOIN un_data AS d ON (c.norm_id =  d.type2_norm_id)
    LEFT JOIN exp_weblog_titles AS wt USING (entry_id)
WHERE (c.parent_id != '') AND (wt.year = 2014) AND (c.`type_id` = 2) OR (c.norm_id = 71) 
GROUP BY parent
ORDER BY parent ASC;

result

我需要过滤第二个表(第2列)中的数据,同时保持结构(第1列和第3列)而不进行过滤。我该怎么做?

1 个答案:

答案 0 :(得分:0)

当外连接时,不要将外表条件放在WHERE子句中,然后放在ON子句中。 (否则外部联接将作为常规内部联接...)

 SELECT (
    CASE 
       WHEN (c.`norm_id` = 71) THEN 71
       ELSE c.parent_id
    END) AS parent, 
    SUM(d.number) AS parent_sum,
    COUNT(DISTINCT(c.norm_id)) AS child_cnt
FROM un_catalog AS c
    LEFT JOIN un_data AS d ON (c.norm_id = d.type2_norm_id)
    LEFT JOIN exp_weblog_titles AS wt ON wt.entry_id = XXX.entry_id AND (wt.year = 2014)
WHERE (c.parent_id != '')  AND (c.`type_id` = 2) OR (c.norm_id = 71) 
GROUP BY parent
ORDER BY parent ASC;

请注意,我不知道哪个表entry_id属于哪个,所以用c或d替换上面的XXX! (USING ...)