我正在尝试编写一些sql来访问用户个人资料以及他们访问其他个人资料。
数据库架构
mysql> desc user_views;
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| user_id | mediumint(8) | NO | PRI | 0 | |
| visitor_id | mediumint(8) | NO | PRI | 0 | |
| created_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+-------+
mysql> desc users;
+--------------------+----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+----------------+------+-----+---------+----------------+
| id | mediumint(8) | NO | PRI | NULL | auto_increment |
| first_name | varchar(255) | YES | | NULL | |
| last_name | varchar(255) | YES | | NULL | |
| email_address | varchar(255) | NO | UNI | NULL | |
| username | varchar(128) | NO | UNI | NULL | |
| algorithm | varchar(128) | NO | | sha1 | |
| salt | varchar(128) | YES | | NULL | |
| password | varchar(128) | YES | | NULL | |
| is_active | tinyint(1) | YES | MUL | 1 | |
+--------------------+----------------+------+-----+---------+----------------+
我的访问者SQL
仅向用户显示一次。例如,如果我刷新用户A的个人资料3次,将显示最近的访问次数。我想跟踪每次访问,以便告诉用户他们独特的观点和总体观点。
SELECT v.visitor_id FROM user_views v, users u, users u2
WHERE v.user_id = :user_id AND v.visitor_id != :user_id
AND u.id = v.user_id AND u2.id = v.visitor_id
AND u.is_active = 1 AND u2.is_active = 1
AND NOT EXISTS
(
SELECT * FROM user_profile_view v2
WHERE v2.visitor_id = v.visitor_id
AND v2.created_at > v.created_at
)
ORDER BY v.created_at DESC LIMIT 0, 10
访问过的SQL
再次相同。用户只会显示一次。
SELECT v.user_id FROM user_views v, users u, users u2
WHERE v.user_id != :visitor_id AND v.visitor_id = :visitor_id
AND u.id = v.user_id AND u2.id = v.visitor_id
AND u.is_active = 1 AND u2.is_active = 1
AND NOT EXISTS
(
SELECT * FROM users_view v2
WHERE v2.user_id = v.user_id AND v2.created_at > v.created_at
)
GROUP BY v.user_id
ORDER BY v.created_at DESC LIMIT 0, 10
SQL工作正常,但我想知道您是否认为SQL可以改进,或者我应该以更有效的方式编写它。