考虑以下表格:
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.ID
和WHERE 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
我可能不够清楚,请查看下面的示例数据:
显然,第一个查询的Name
字段将返回John,并返回第二个查询的Chris。我想在一个查询中显示两个名称。
答案 0 :(得分:1)
您实际上正在加入每个行,然后过滤掉只保留您想要的行。您应该使用连接过滤掉它们:
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 5.1.46):
+-------+ | Name | +-------+ | John | | Chris | +-------+
编辑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);
答案 1 :(得分: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