Advertisement
Guest User

Untitled

a guest
Jun 18th, 2021
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 2.04 KB | None | 0 0
  1. I have following table
  2.  
  3. | Id| source_url | target_url | event_type |
  4. |:---- |:------:| -----:| -----:|
  5. | 1| http://google.com/| http://mypage.com/example | 0 |
  6. | 1| http://google.com/| http://mypage.com/otherpage| 0 |
  7. | 2| http://google.com/| http://mypage.com/example | 0 |
  8. | 3| http://google.com/| http://mypage.com/example | 0 |
  9. | 4| http://mypage.com/example| http://otherdomain.com/example | 1 |
  10. | 5| http://mypage.com/example| http://otherdomain.com/example | 1 |
  11. | 5| http://mypage.com/otherpage| http://otherdomain.com/example | 1 |
  12.  
  13. Here `event_type = 0` is Visit and `event_type = 1` is Click
  14.  
  15. Using following query I can get **visits** on each url
  16.  
  17.  
  18.     SELECT
  19.         target_url,
  20.         COUNT(target_url) AS visits
  21.     FROM
  22.         tbl_events
  23.     WHERE
  24.         event_type = 0 AND target_url <> ''
  25.     GROUP BY
  26.         target_url
  27.     ORDER BY
  28.         visits
  29.     DESC
  30.         ;
  31.  
  32.  
  33. ### Visits
  34.  
  35.  
  36. | target_url | visits |
  37. |:---- |:------:|
  38. | http://mypage.com/example| 3|
  39. | http://mypage.com/otherpage | 1|
  40.  
  41. And with following query i can get clicks
  42.  
  43.  
  44.     SELECT
  45.         source_url,
  46.         COUNT(source_url) AS clicks
  47.     FROM
  48.         event_tracking
  49.     WHERE
  50.         event_type = 1 AND source_url <> ''
  51.     GROUP BY
  52.         source_url
  53.     ORDER BY
  54.         clicks
  55.     DESC
  56.         ;
  57.  
  58. ### Clicks
  59.  
  60.  
  61. | source_url | clicks |
  62. |:---- |:------:|
  63. | http://mypage.com/example| 2|
  64. | http://mypage.com/otherpage| 1|
  65.  
  66.  
  67.  
  68. ### Desired Result
  69.  
  70.  
  71. I want my final result to be like below ***without using subquery*** (since original table contains more than 1 million rows and subquery takes too long)
  72.  
  73.  
  74. | url | clicks | visits |
  75. |:---- |:------:| -----:|
  76. | http://mypage.com/example| 2| 3|
  77. | http://mypage.com/otherpage| 1| 1|
  78.  
  79. Right now, I feel like I have to create a temporary table and use `ON DUPLICATE KEY UPDATE` and use url as primary key, but I feel like there might be a better way and I couldn't figure out.
  80.  
  81. ***Is there any way to achieve this result without using subquery and temporary table?***
  82.  
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement