2010-12-16 35 views
-1

考慮以下表:在不同的地方在同一領域的條件在MySQL中加入表?

account => ID, Login, Pass, Email, Level, IDNum, Name 
records => RID, Status, IDNum, Reason, Type, Amount, Date, SubmitterID 

現在我加入用下面的查詢表:

SELECT account.Name FROM account, records WHERE records.IDNum = account.IDNum 

在上面的名稱字段的查詢將基於匹配IDNUM加盟,但是如果我想要同時獲得名稱字段WHERE account.ID = records.IDWHERE records.IDNum = account.IDNum,這可能嗎?

SELECT account.Name FROM account, records WHERE records.IDNum = account.IDNum 
SELECT account.Name FROM account, records WHERE records.SubmitterID = account.ID 

我可能不夠清晰,請檢查下面的示例數據:

alt text

如此明顯的

總之,加入以下2個查詢分成一個問題第一個查詢的Name字段將返回John,並返回Chris進行第二個查詢。我想在一個查詢中顯示兩個名稱。

+0

你有什麼MySQL版本,我的5.0只是盯着我,如果我嘗試這樣的'連接'。 – Bobby 2010-12-16 10:49:04

+0

@Bobby:對不起,糾正了我的查詢。我有MySQL 5.0.91。 – user435216 2010-12-16 10:50:54

回答

1

你實際上joinging EVERY行,然後過濾掉只保留一個你想要的。而是應該將篩選出來的權利與參與:

select account.Name 
FROM account 
    INNER JOIN records ON (records.IDNum = account.IDNum AND records.SubmitterID = account.ID)

編輯:由OP問題編輯

看來你需要和OR代替AND在上面JOIN。因此:

select account.Name 
FROM account 
    INNER JOIN records ON (records.IDNum = account.IDNum OR records.SubmitterID = account.ID)

編輯2:隨訪由OP

create table account (id int, IDNum int, Name char(5)); 
insert into account values (1, 12345, 'John'), (2, NULL, 'Chris'); 
create table records (RID int, IDNum int, SubmitterID int); 
insert into records values (1, 12345, 2); 
select account.Name 
FROM account 
    INNER JOIN records ON (records.IDNum = account.IDNum OR records.SubmitterID = account.ID); 

產率(與MySQL 46年5月1日)發表評論:

+-------+ 
| Name | 
+-------+ 
| John | 
| Chris | 
+-------+

EDIT 3:到OP第二條評論:

是這樣的嗎?

select account.Name as byIDNum, NULL bySubmitterID 
from account 
    inner join records USING (IDNum) 
union 
select NULL, account.Name 
from account 
    inner join records ON (records.SubmitterID = account.ID);
+0

感謝您的編輯。然而,這隻會爲Name字段返回一個(單個)值,不管是「records.IDNum = account.IDNum」還是「records.SubmitterID = account.ID」。我需要同時使用兩個名稱字段。這看起來很奇怪嗎? – user435216 2010-12-16 11:35:27

+0

@ user435216:對不起,我的MySQL版本沒有得到相同的結果。 – Danosaure 2010-12-16 11:52:49

+0

謝謝,非常感謝你的幫助。第一個和第二個過濾器的結果可以保存到兩個不同的列中嗎?就像創建某種別名一樣。而且我真的很抱歉我的英語不好,在開始時無法清楚地解釋我的問題。 – user435216 2010-12-16 12:20:06

0

我可能誤解了,但不會簡單並完成你所需要的?

SELECT account.name 
FROM account, records 
WHERE records.IDNum = account.IDNum 
AND records.SubmitterID = account.id 

或者,如果你想獲得回報情形之一的,這些規則是正確的:

SELECT account.name 
FROM account, records 
WHERE records.IDNum = account.IDNum 
OR records.SubmitterID = account.id 
+0

非常抱歉我的問題不夠清楚,請檢查我的更新問題。謝謝。 – user435216 2010-12-16 11:16:59

相關問題