Insert Records in a Table without duplicating the

2019-09-20 08:44发布

问题:

I have this MySQL Statement. I want to execute this SQL repeatedly to insert the result into a Third table withoud duplicating the Records in Third Table.

SELECT  `Client_ID`, `Client_RFID_Number` 
FROM ciom_master AS a
WHERE  (`Client_Active` ='Y' OR `Client_Active` ='y')
    AND NOT EXISTS (
                    SELECT (`Client_Check_Out`)
                    FROM `cio_master` AS b
                    WHERE a.Client_ID = b.Client_ID 
                        and Client_Check_Out = CURDATE() )
 AND NOT EXISTS (
                 SELECT (`Client_Check_In`)
                 FROM `cio_master` AS c
                 WHERE a.Client_ID = c.Client_ID 
                     and Client_Check_In = CURDATE())

I am attempting following Statement but it is throwing error

INSERT IGNORE INTO cio_alert (`Client_ID`, `Client_RFID_Number`, `Client_Check_Out`, `Client_Check_In`)

SELECT `ciom_master`.`Client_ID`, `ciom_master`.`Client_RFID_Number`,`cio_master`.`Client_Check_Out`, `cio_master`.`Client_Check_In`  FROM ciom_master 
INNER JOIN `cio_master` ON `ciom_master`.`Client_ID` = `ciom_master`.`Client_ID`
 WHERE  EXISTS 
 (SELECT  `Client_ID`, `Client_RFID_Number` 
    FROM ciom_master AS a
    WHERE (`Client_Active` ='Y' OR `Client_Active` ='y')
        AND NOT EXISTS (
                    SELECT (`Client_Check_Out`)
                    FROM `cio_master` AS b
                    WHERE a.Client_ID = b.Client_ID 
                        and Client_Check_Out = CURDATE() )
        AND NOT EXISTS (
                 SELECT (`Client_Check_In`)
                 FROM `cio_master` AS c
                 WHERE a.Client_ID = c.Client_ID 
                     and Client_Check_In = CURDATE())
        AND (
                SELECT `Client_Check_Out` FROM cio_master 
                WHERE ((`Client_Check_Out` IS NOT NULL AND `Client_Check_In` IS NULL) 
                 OR (`Client_Check_Out` IS NULL AND `Client_Check_In` IS NULL)))
        AND (
                SELECT `Client_Check_In` FROM cio_master 
                WHERE ((`Client_Check_Out` IS NOT NULL AND `Client_Check_In` IS NULL) 
                 OR (`Client_Check_Out` IS NULL AND `Client_Check_In` IS NULL)))         
 )

回答1:

You didnt mention exist or not exist condition at the last select statement... u simply put the and condition without any exist or not exist or in or not in. Try to put any of the valid condition over there. And also in the first select statement y r u using same table twice and joining without any alias try to check that one also once.



标签: insert