2014-03-26 94 views
0

我想從mysql表中檢索一個值,並與使用mysql查詢的三個表進行比較。如何從mysql表中使用mysql查詢從三個表中檢索值?

我的表:

main_tbl: 

id name email_id 
-------------------- 
1 test [email protected] 

Login_tbl: 

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


sublogin_tbl: 

login_id id name emailid 
------------------------ 
2  1 priya [email protected] 

如果我輸入一個用戶名作爲「阿爾亞」首先,它檢查與LOGIN_ID在sublogin_tbl存在,如果值存在,意味着它檢索值(名稱,EMAILID)從sublogin_tbl否則返回來自main_tbl的值。

+0

以及如何檢查與'main_tbl'?你錯過了'main_tbl'中的'login_id'嗎? –

+0

不,我不使用main_tbl中的login_id – ahalya

+0

,然後在'main_tbl'中比較哪一列? 'id'本身? –

回答

0

它不清楚你想要什麼。讓我們通過你需要一句一句

如果我輸入一個用戶名作爲「阿爾亞」首先,它與LOGIN_ID檢查存在

'passing @username - ahalya 

declare @intId as int; 
Select @intId = (Select id from Login_tbl where [email protected]) 

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

    Select name,emailid from sublogin_tbl where [email protected] 

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 
0

如果你正在尋找的結果單查詢,則這可以用於(但是,只有當login_tblidmain_tblid相比 - 否則你必須做出一些改變):

這裏是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 
0

這將是最好創建一個存儲過程,並把別人是否在conditon存儲過程中,以檢查是否登錄ID存在....

CREATE PROCEDURE過程名 (@username爲nvarchar(50)) 作爲 聲明@counter INT = 0 集@計數器=選擇計數從sublogin_tbl (ID) 其中name = @ userName的