如何使用mysql查询从三个表中检索mysql表中的值?

时间:2014-03-26 10:39:31

标签: mysql

我想从mysql表中检索一个值,使用mysql查询与三个表进行比较。

我的表格:

main_tbl:

id  name   email_id
--------------------   
1   test  test@gmail.com

Login_tbl:

login_id id  username
---------------------
1        1   anu
2        1   ahalya


sublogin_tbl:

login_id id  name   emailid 
------------------------
2       1   priya  priya@gmail.com

如果我输入用户名为" ahalya"首先它检查login_id是否存在于sublogin_tbl中,如果value存在意味着它从sublogin_tbl检索值(name,emailid),否则返回main_tbl中的值。

3 个答案:

答案 0 :(得分:0)

目前还不清楚你想要什么。让我们一句一句地讨论你的需要

如果我首先输入用户名为“ahalya”,则使用login_id exists

进行检查
'passing @username - ahalya

declare @intId as int;
Select @intId = (Select id from Login_tbl where username=@username )

if @intId >0 'login_id exists :retrieve the values(name,emailid) from sublogin_tbl
begin

   Select name,emailid from sublogin_tbl where id=@intId

end

else 'otherwise it returns the values from main_tbl.
begin

   'Here i don't know what exactly you want, we are searching by username and its only present in login table, put where in below as per your need !

    select * from main_tbl 

end

答案 1 :(得分:0)

如果您在单个查询中查找结果,则可以使用(但仅当login_tbl idmain_tbl id进行比较时 - 否则您必须做一些改变):

以下是Fiddle

select name,emailid from sublogin_tbl where login_id = 
(select login_id from login_tbl where username='ahalya')
union
select name,email_id from main_tbl where id = 
(select id from login_tbl where username='ahalya')
Limit 1

答案 2 :(得分:0)

最好创建一个存储过程并在存储过程中放入if else conditon来检查登录ID是否存在....

创建过程procedureName (@userName nvarchar(50)) 如 声明@counter int = 0 set @ counter =选择计数(id) 来自sublogin_tbl 其中name = @ userName