How can I check two conditions before inserting?

后端 未结 3 1334
忘掉有多难
忘掉有多难 2020-12-30 17:57

I have three tables:

// Posts
+----+----------+---------------+-----------+
| id |  title   |    content    | id_author |
+----+----------+---------------+--         


        
相关标签:
3条回答
  • 2020-12-30 18:24
    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;
    

    then you set parameter user equal to the current user id.

    EDIT: I suppose id_user in table Votes must be the voter's id, not the author of the post (correct?), so I fixed the query eliminating the JOIN.

    0 讨论(0)
  • 2020-12-30 18:41

    Use and with where

    INSERT INTO Votes (id_post,id_user)
    SELECT ?,?
    FROM Posts p, Users u 
    WHERE p.id_user = :author and u.active = 1 limit 1;
    
    0 讨论(0)
  • 2020-12-30 18:43
    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;
    
    0 讨论(0)
提交回复
热议问题