SELECT语句中匹配的REGEXP模式

时间:2015-09-07 13:43:10

标签: mysql regex

想象一下,有一个包含用户点击次数的点击表。现在我想选择每个社交网络的总点击次数:

UPD: refererHost列包含任何referer主机,而不仅仅是社交网络主机。

    SELECT
        c.refererHost as referer,
        COUNT(c.id) as clicks
    FROM clicks c
    WHERE c.referrerHost REGEXP 'facebook|google|linkedin'
    GROUP BY referer
    ORDER BY clicks desc

但问题是referer字段将包含像www.facebook.com这样的域名,我需要选择匹配的regexp值(例如' facebook')。可以用MySQL做到吗?

1 个答案:

答案 0 :(得分:1)

最初,我完全摆脱了REGEXP并继续:

  SELECT CASE 
           WHEN c.referrerHost LIKE '%facebook%' THEN 'facebook' 
           WHEN c.referrerHost LIKE '%google%'   THEN 'google' 
           WHEN c.referrerHost LIKE '%linkedin%' THEN 'linkedin'
         END referrer,
         COUNT(c.id) as clicks
    FROM clicks c
   WHERE c.referrerHost LIKE '%facebook%'
      OR c.referrerHost LIKE '%google%'  
      OR c.referrerHost LIKE '%linkedin%' 
GROUP BY referer
ORDER BY clicks desc

我相当肯定你会获得更好的表现,但如果需要你可以进行基准测试。

然而,理想情况下,我很想建立一个带有表格的正确推荐系统:

  • referer - id,host,title
  • click - id,referrer_id

您可以在进入网站时计算推介,如果您控制网址,则可以使用referrer_id轻松配置。

然后您的SQL变为:

  SELECT r.title as referer,
         COUNT(c.id) as clicks
    FROM clicks c
    JOIN referrer r
      ON r.id = c.referrer_id
GROUP BY referer
ORDER BY clicks desc