sql嵌套连接内连接和左连接

时间:2013-08-14 15:50:45

标签: mysql sql join

您好我想使用带有跟踪列表的MySQL过滤日志。

每个日志都属于服务器,

每次跟踪属于服务器并且具有0..N模式

每个模式都属于跟踪

我有3张桌子:

logs     : |  id  |      ip     | url     | server_id | ...
tracking : |  id  | server_id   | name    | other fields...
pattern  : |  id  | tracking_id | pattern |

我想计算与特定服务器的跟踪匹配的日志我的问题是我的查询混淆了具有模式的跟踪和不具有模式的跟踪。

SQL小提琴:http://sqlfiddle.com/#!2/f11b1/2

SELECT COUNT(DISTINCT logs.ip), tr.name
FROM `logs`
INNER JOIN `trackings` as tr ON 
        ( tr.server_id = logs.server_id )
        AND -- OTHER conditions between log and tracking
    LEFT JOIN `patterns` as pt ON 
        ( pt.tracking_id = tr.id )
        AND (logs.url LIKE pt.pattern )
GROUP BY tr.id

我的问题在于第二次加入,如果我使用INNER JOIN patterns as pt ON我得到了正确的结果,但仅限于具有某些模式的跟踪, 如果我使用LEFT JOIN patterns as pt ON我会得到所有跟踪,但会有错误计数(我得到SELECT COUNT(DISTINCT logs.ip) FROM logs的结果)

修改 我可以通过跟踪中的字段获得正确的结果,该字段指示跟踪是否具有模式和UNION:

(
SELECT COUNT(DISTINCT lg.ip), tr.name
FROM `logs` as lg
INNER JOIN `trackings` as tr ON 
        ( tr.server_id = lg.server_id )
        AND (tr.hasPatterns = 1)
        AND -- Other conditions
    INNER JOIN `patterns` as pt ON 
        ( pt.tracking_id = tr.id )
        AND (lg.url LIKE pt.pattern )
WHERE
GROUP BY tr.id
)
UNION
(
SELECT COUNT(DISTINCT lg.ip), tr.name
FROM `logs` as lg
INNER JOIN `trackings` as tr ON 
        ( tr.server_id = lg.server_id )
        AND (tr.hasPatterns = 0)
WHERE
GROUP BY tr.id, lg.date
)

但我想有一种方法可以不使用Union ...

1 个答案:

答案 0 :(得分:0)

你可以在count内添加一个条件,所以我认为以下是你想要的:

SELECT COUNT(DISTINCT (case when tr.hasPatterns = 1 and pt.tracking_id is not null
                            then lg.ip
                            when tr.hasPatterns = 0
                            then lg.ip
                       end)), tr.name
FROM `logs` as lg
INNER JOIN `trackings` as tr ON 
        ( tr.server_id = lg.server_id )
        AND -- Other conditions
    LEFT JOIN `patterns` as pt ON 
        ( pt.tracking_id = tr.id )
        AND (lg.url LIKE pt.pattern )
WHERE
GROUP BY tr.id

编辑:

这会返回你想要的东西:

SELECT COUNT(DISTINCT (case when tr.size = 0 and pt.tracking_id is not null
                            then lg.ip
                            when tr.size > 0 and lg.size > tr.size
                            then lg.ip
                       end)), tr.name
FROM `logs` as lg
INNER JOIN `trackings` as tr ON 
        ( tr.server_id = lg.server_id )
    LEFT JOIN `patterns` as pt ON 
        ( pt.tracking_id = tr.id )
        AND (lg.url LIKE pt.pattern )
GROUP BY tr.id;

您的SQL小提琴具有附加条件lg.size > tr.size,这不在原始问题中。