简体   繁体   中英

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:

SELECT * FROM `member` WHERE `ID`=2

Which returns the data from the table member .

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 .

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. 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

Simple join, between a common 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

 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.

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. If you want to get a result in this case, you can try 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM