问题描述
我一直在设法了解如何使用单个查询从我的两个表中选择数据.如果有人能提出比单次查询更好的方法,那我真是无所适从!以前,我会使用两个查询来做到这一点,尽管我被认为是一个查询会更好,所以我尝试学习.
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
我想做的是在表member
上运行查询,例如:
What I'm trying to do is run a query on the table member
like:
SELECT * FROM `member` WHERE `ID`=2
从表member
返回数据.
但是,我也希望从表networking
中返回相关值.表member
中的列networkingID
是networking
中行的ID
.
However I also wish to return the relating value from the table networking
. The column networkingID
in the table member
is the ID
of the row in networking
.
我该怎么做?
到目前为止,我已经尝试过使用可以通过Google找到的所有JOIN,但无法使其正常运行.我最好的结果是使用LEFT JOIN
,其中所有列均存在,但联网表的结果均为NULL
.
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. 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
.
推荐答案
SELECT * FROM member
LEFT JOIN networking
ON member.networkingID=networking.ID
WHERE member.ID=2
这篇关于如何使用一个查询从两个表中选择数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!