我试图在一个查询中为验证序列整理SQL语句。
用户
╔════╦══════════════╦══════════╗
║ id ║ emailAddress ║ password ║
╠════╬══════════════╬══════════╣
║ 1 ║ test1 ║ pass1 ║
║ 2 ║ test2 ║ pass2 ║
║ 3 ║ test3 ║ pass3 ║
╚════╩══════════════╩══════════╝
user_token
╔═══════╦═════════╗
║ token ║ user_id ║
╠═══════╬═════════╣
║ t1 ║ 1 ║
║ t2 ║ 2 ║
║ t3 ║ 3 ║
╚═══════╩═════════╝
我的尝试(部分)请注意我可以组合由;
条件插入
INSERT INTO user_token(token, user_id)
SELECT ?, ? FROM DUAL
WHERE EXISTS (SELECT * FROM user WHERE emailAddress = ? AND password = ?);
["t1", 1, "test1", "pass1"];
设置某种变量,尝试与其他尝试结合使用。
SELECT @id:=id, emailAddress, password FROM user WHERE emailAddress = "test1" AND password = "pass1";
我想我已经关闭,但是在子查询之外访问@id时遇到了问题。
serviceRequest.sql = "INSERT INTO user_token(token, user_id)\
SELECT ?, @id FROM DUAL WHERE EXISTS (
SELECT @id:=id, emailAddress, password FROM user WHERE emailAddress = ? AND password = ?
);
SELECT @id, ? FROM DUAL";
serviceRequest.values = ["t1", "test1", "pass1", "t1"];
目标:
在单个事务/执行中组合多个使用逻辑的SQL语句,以实现身份验证过程,借助IF
子句和SQL等用户定义的变量。
答案 0 :(得分:0)
也许您正在寻找last_insert_id()
和row_count()
。为了安全起见,我会将这些分配给变量:
INSERT INTO user_token(token, user_id)
SELECT ?, ? FROM DUAL
WHERE EXISTS (SELECT * FROM user WHERE emailAddress = ? AND password = ?);
SELECT @row_count := ROW_COUNT(), @last_insert_id = LAST_INSERT_ID();
SELECT u.*
FROM user
WHERE @row_count > 0 AND emailaddress = ? and password = ?;
我不确定这是你想要的,但这确实显示了你可能需要的两个功能的使用。
答案 1 :(得分:0)
最终破解了它,但我需要对查询#2进行改进,使用IF而不是在SELECT
任何人中执行另一个WHERE EXISTS
语句?
serviceRequest.sql = "SET @emailAddress = ?, @password = ?;\
SELECT @authToken:= ? AS authToken, @id:=id AS id FROM user WHERE emailAddress = @emailAddress AND password = @password;\
INSERT INTO user_token(authToken, user_id) \
SELECT @authToken, @id FROM DUAL WHERE EXISTS (SELECT id FROM user WHERE emailAddress = @emailAddress AND password = @password);";
serviceRequest.values = [request.body.credentials.emailAddress, request.body.credentials.password, "t3"];
查询#1 。检索到第一个用户记录,并设置变量(@token
,@id
)并作为结果集返回。
查询#2 。如果记录存在,则执行user_token insert
感谢有人可以改进此答案并进一步优化查询,尤其是查询#2,其他选择语句正在进行中,我相信WHERE EXISTS
可以利用检查@id
是否为values
插入不会为空,我不必在<div class="order-form">
<div class="checkout-left">
<div class="video another-video">
<div class="video-wrapper second-video">
<video class="video-js vjs-default-skin" controls preload="auto" width="221" height="169">
<source src="magnet.mp4" type="video/mp4">
</video>
</div>
</div>
</div>
<img src="http://magnaboss.com/wp-content/themes/twentyfifteen/images/checkout-right.jpg" style="float: right;" />
<img src="http://magnaboss.com/wp-content/themes/twentyfifteen/images/product-2.png" class="product-2" />
<div style="clear:both;"></div>
</div>
数组中传递两次用户名/密码。