在MySQL(phpmyadmin和MySQL workbench的两个实例)中,我想检查一个表中是否存在值,然后再对同一个表或其他表执行任何其他查询,以下是我尝试过的查询集但是它们都没有工作并且都给出了错误,对于形成复杂查询来说是新手,所以要小心忽略在形成这些查询时我必须犯的任何语法错误
查询1
SELECT CASE WHEN ( (SELECT * FROM likes WHERE face_id = 'mm' AND phone_id = 'pp') > 1 )
THEN ( SELECT CASE WHEN ( (SELECT * FROM dislikes WHERE face_id = 'mm' AND phone_id = 'pp') > 1)
THEN ( DELETE FROM likes WHERE face_id = 'mm' AND phone_id = 'pp' )
ELSE SELECT * FROM likes
END
)
ELSE INSERT INTO likes (face_id, phone_id) VALUES ('mm', 'pp')
END
查询2
IF EXISTS ( SELECT * FROM likes WHERE face_id = 'mm' AND phone_id = 'pp')
IF EXISTS ( SELECT * FROM dislikes WHERE face_id = 'mm' AND phone_id = 'pp')
DELETE FROM likes WHERE face_id = 'mm' AND phone_id = 'pp'
ELSE
SELECT * FROM likes
ELSE/*Else of first IF*/
INSERT INTO likes (face_id, phone_id) VALUES ('mm', 'pp')
END
中选择了我的选择
我有2张桌子,不喜欢和不喜欢;两个表都有三个字段id,face_id和phone_id。进入喜欢表的数据/值不得出现在不喜欢的表中,因此,例如,如果我希望在喜欢的表中插入一些值,我会检查我的喜欢表中是否存在这些值,然后插入我的值和返回true
但如果它存在,我会检查它是否也存在于不喜欢的表中,如果是,我会从不喜欢的表中删除它,如果没有,就不会发生任何事情。
答案 0 :(得分:2)
如上所述,在运行普通查询时,您无法执行更新,插入或删除,因此它必须是我的数据库中的存储过程,并且我创建了一个这样的存储过程
BEGIN
IF(SELECT COUNT(*) FROM expressions WHERE face_id = face_id_ AND phone_id = phone_id_ = 1 )
THEN UPDATE expressions SET expression = express_ WHERE face_id = face_id_ AND phone_id = phone_id_;
ELSE INSERT INTO expressions (face_id, phone_id, expression) VALUES (face_id_, phone_id_, express_);
END IF;
END
然后使用PDO
在我的查询中调用它SET SQL_SAFE_UPDATES = 0;
call update_expressions(:pid, :fid, :exp);
答案 1 :(得分:0)
这里没什么可说的。但是下面呢?
/*Two queries*/
DELETE FROM LIKES
WHERE FACE_ID IN (SELECT FACE_ID
FROM LIKES a, DISLIKES b
WHERE FACE_ID = 'mm'
AND PHONE_ID = 'pp'
AND a.FACE_ID = b.FACE_ID
AND a.PHONE_ID = b.PHONE_ID)
/
/*All likes that are not in likes*/
INSERT INTO LIKES
SELECT FACE_ID, PHONE_ID FROM DISLIKES
MINUS
SELECT FACE_ID, PHONE_ID FROM LIKES