lundi 5 août 2019

Checking if the record exist in different table

I'm working on a project with the tables c_sent_messages which store sent messages from users, c_passwords which stores passwords for promotions and c_received_messages that stores the sent messages to the users from the system. I want to check if the password exists that user sent, in the c_passwords table. If exists, i want to delete the record from c_passwords table.

The code that shown below i tried. It seems ok to me but i got some errors and syntax issues i think.

DELIMITER $$
CREATE PROCEDURE flood () BEGIN
    DECLARE
        i INT DEFAULT 0;
    myloop :
    LOOP
        IF
            EXISTS ( SELECT c_passwords.pass FROM c_passwords WHERE c_passwords.pass = c_sent_messages.msg_text ) THEN-- IF c_sent_messages.stats = "N" THEN
            IF
                EXISTS ( SELECT c_sent_messages.stats FROM c_sent_messages WHERE c_sent_messages.stats = "N" ) THEN
                    INSERT INTO c_received_messages ( receiver, sender, msg_text, `status`, x_date )
                VALUES
                    (
                        c_sent_messages.sender,
                        "5757",
                        "Code is received successfully.",
                    NOW());
                ELSE INSERT INTO c_received_messages ( receiver, sender, msg_text, `status`, x_date )
                VALUES
                    (
                        c_sent_messages.sender,
                        "5757",
                        "Code is used before!",
                    NOW());

            END IF;
            ELSE INSERT INTO c_received_messages ( receiver, sender, msg_text, `status`, x_date )
            VALUES
                (
                    c_sent_messages.sender,
                    "5757",
                    "Please send a valid code!",
                NOW());

        END IF;
        DELETE 
        FROM
            c_passwords 
        WHERE
            pass = c_sent_messages.msg_text;

        SET i = i + 1;
        IF
            i = 100 THEN
                LEAVE myloop;

        END IF;

    END LOOP myloop;

END $$DELIMITER;

When i CALL flood(); it shows the error 1054 - Unknown column 'c_sent_messages.msg_text' in 'where clause' What's wrong in my syntax? How to fix it? Or does anyone know the other way?

Aucun commentaire:

Enregistrer un commentaire