您好我正在尝试执行此简单语句但我想添加一个来自select的变量。这就是我所拥有的。
userEmail varChar(50) := SELECT user_id FROM users WHERE email = 'email@email.com';
SELECT *
FROM iphone_alerts
WHERE user_id = userEmail
AND date_added = (SELECT MAX(date_added) FROM iphone_alerts WHERE user_id = userEmail
我是否需要使用Declare和Begins的内容?我是sql的新手,我很难找到答案。
答案 0 :(得分:4)
你需要:
declare
userEmail varchar2(200);
begin
select user_id into userEmail
from users
where email = 'email@email.com';
-- you will need a cursor to itare these results
select *
from iphone_alerts
where user_id = userEmail
and date_added = (select max(date_added) from iphone_alerts WHERE user_id);
end;
评论后编辑:
如果select只返回一行,则不需要游标,但需要into
子句将每个检索到的值存储到变量中。类似的东西:
declare
userEmail varchar2(200);
v_field1 number;
v_field2 date;
v_field3 varchar2(200);
begin
select user_id into userEmail
from users
where email = 'email@email.com';
-- you will need a cursor to itare these results
select field1, field2, field3
into v_field1, v_field2, v_field3
from iphone_alerts
where user_id = userEmail
and date_added = (select max(date_added) from iphone_alerts WHERE user_id);
end;
答案 1 :(得分:2)
如果你想在SQL中这样做,你需要像
这样的东西SELECT alerts.*
FROM iphone_alerts alerts,
users
WHERE alerts.user_id = users.user_id
AND users.email = 'email@email.com'
AND alerts.date_added = (SELECT MAX(date_added)
FROM iphone_alerts alerts2
WHERE alerts2.user_id = user.user_id)
这样的效率可能会让我们只打一次IPHONE_ALERTS表。
SELECT <<list of columns in IPHONE_ALERTS>>
FROM (
SELECT alerts.*,
RANK() OVER (PARTITION BY alerts.user_id ORDER BY date_added DESC) rnk
FROM iphone_alerts alerts,
users
WHERE alerts.user_id = users.user_id
AND users.email = 'email@email.com'
)
WHERE rnk = 1
答案 2 :(得分:0)
我不确定你要做什么,但我认为你可能需要select into
declare
V_userID varChar(50) ;
begin
/*This will store the value of the user_id field into the v_userID variable.*/
SELECT user_id into v_userID FROM users WHERE email = 'email@email.com';
end;
http://download.oracle.com/docs/cd/B13789_01/appdev.101/b10807/13_elems045.htm