我有三张桌子:
// Posts
+----+----------+---------------+-----------+
| id | title | content | id_author |
+----+----------+---------------+-----------+
| 1 | title1 | content1 | 1234 |
| 2 | title2 | content2 | 5678 |
+----+----------+---------------+-----------+
// Users
+----+--------+--------+
| id | name | active |
+----+--------+--------+
| 1 | jack | 1 |
| 2 | peter | 0 |
| 3 | John | 1 |
+----+--------+--------+
// Votes
+----+---------+---------+
| id | id_post | id_user |
+----+---------+---------+
| 1 | 32 | 1234 |
| 2 | 634 | 5678 |
| 3 | 352 | 1234 |
+----+---------+---------+
现在我需要在将新投票插入Votes
表之前检查两个条件:
Posts.id_user = :author
(我知道我可以通过FK做到这一点,但我不想要) Users.active = 1
这也是我的疑问:
INSERT INTO Votes (id_post,id_user)
SELECT ?,?
FROM Posts p
WHERE p.id_user = :author limit 1;
如何在查询中添加第二个条件Users.active = 1
?
编辑:实际上,我试图让人们无法投票(active = 0
)。例如,如果SO禁止男性,那么我就不能投票发布了,因为我(当前用户)被禁止了。因此,我非常确定在查询中应该使用$_SESSION['id']
。
答案 0 :(得分:1)
INSERT INTO Votes (id_post,id_user)
SELECT p.id,u.id
FROM Posts p, Users u
WHERE p.id_user = :author
AND u.id = :user
AND u.active = 1 limit 1;
然后将参数user
设置为等于当前用户ID。
编辑:我认为表id_user
中的Votes
必须是投票人的ID,而不是帖子的作者(正确吗?),所以我修复了查询消除了JOIN
。
答案 1 :(得分:0)
使用和在哪里
INSERT INTO Votes (id_post,id_user)
SELECT ?,?
FROM Posts p, Users u
WHERE p.id_user = :author and u.active = 1 limit 1;
答案 2 :(得分:0)
INSERT INTO Votes (id_post,id_user)
SELECT p.id, u.id
FROM Posts p
INNER JOIN Users u ON 1 = 1
WHERE p.id_user = :author
AND u.id = :current_user_id
AND u.active = 1
LIMIT 1;