[英]How to select data from two tables using a single query
I've been trying to get my head around how to use a single query to select data from two of my tables.我一直在思考如何使用单个查询从我的两个表中选择数据。 If anybody can suggest a better way than a single query, I'm all ears!如果有人能提出比单个查询更好的方法,我会全神贯注! Previously I would do this using two queries which I could make work easily although I'm led to believe that a single query would be better, hence trying to learn.以前我会使用两个查询来做到这一点,尽管我相信单个查询会更好,但我可以轻松完成工作,因此我正在努力学习。
One of my tables resembles this in a cut down form.我的一张桌子以精简的形式与此相似。 Call this table "member":称这个表为“成员”:
ID | firstName | lastName | networkingID
And the other table which I'll call "networking":还有一张我称之为“网络”的表:
ID | websiteURL | facebookURL | twitterURL
What I'm trying to do is run a query on the table member
like:我想要做的是对表member
运行查询,例如:
SELECT * FROM `member` WHERE `ID`=2
Which returns the data from the table member
.它从表member
返回数据。
However I also wish to return the relating value from the table networking
.但是,我也希望从表networking
返回相关值。 The column networkingID
in the table member
is the ID
of the row in networking
.表member
的列networkingID
是networking
中行的ID
。
How would I go about doing this?我该怎么做呢?
So far, I have experimented using all of the JOINs that I was able to find through Google but I am unable to make it work.到目前为止,我已经尝试使用我能够通过 Google 找到的所有 JOIN,但我无法使其工作。 My best result was with a LEFT JOIN
where all of the columns were present but the results from the networking table were all NULL
.我最好的结果是使用LEFT JOIN
,其中所有列都存在,但网络表的结果都是NULL
。
SELECT * FROM member
LEFT JOIN networking
ON member.networkingID=networking.ID
WHERE member.ID=2
Simple join, between a common id.简单连接,在一个公共 ID 之间。 Inner join will ensure there are records in the networking table, otherwise it won't show that member.内连接会确保网络表中有记录,否则不会显示该成员。 you can replace it with a LEFT JOIN
if you want all the member
rows regardless if they have anything joined in the network
table如果您想要所有member
行,无论它们是否在network
表中加入任何内容,您都可以将其替换为LEFT JOIN
SELECT * FROM member m
INNER JOIN networking n
ON (m.networkingID = n.id)
WHERE m.id = 2;
select
*
from
member as m
left outer join
networking as n
on
m.networkingID=n.ID
A JOIN should work. JOIN 应该可以工作。
SELECT * FROM member, networking WHERE member.ID=2 AND member.networkingID=networking.ID
This will return an empty result if there's no networking data for member.ID=2.如果 member.ID=2 没有网络数据,这将返回一个空结果。 If you want to get a result in this case, you can try LEFT JOIN.如果你想在这种情况下得到结果,你可以尝试 LEFT JOIN。
SELECT * FROM member LEFT JOIN networking ON member.networkingID=networking.ID WHERE member.ID=2
select * from member a, networking b
where a.networkingID=b.ID and a.ID = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.