开发者

How to join 3 tables or more in one msql query

开发者 https://www.devze.com 2023-03-16 21:20 出处:网络
Normally I make something like this. #1 first query while () : #2 2nd queries #3 3rd queries endwhile; to get a result. Now I want to combine them in one query. How can be done with this.

Normally I make something like this.

#1 first query
 while () :
    #2 2nd queries
    #3 3rd queries
 endwhile;

to get a result. Now I want to combine them in one query. How can be done with this.

Table#1
----------------------开发者_如何学运维---------------------
SELECT 
UserID, UserName, CountryCode, StateCode, CityCode, VillageCode, UserRace, UserStatus, UpdateStatus 
FROM user_locality
WHERE CountryCode = '{$getCountryCode}'

Table#2
-------------------------------------------
SELECT 
* 
FROM user_addresses 
WHERE address_UserID = '{$UserID}'

Table#3
-------------------------------------------
SELECT 
phone_UserID, phone_m, phone_h, phone_o 
FROM user_phones 
WHERE phone_UserID  = '{$UserID}'

Thank you.


You'll want to use the JOIN clause. There are different types of joins. I'm using LEFT JOIN below which will select all records from user_locality and try to match records from both user_addresses and user_phones.

SELECT    *
FROM      `user_locality`
LEFT JOIN `user_addresses`
ON        `user_addresses`.`address_UserID` = `user_locality`.`UserID`
LEFT JOIN `user_phones`
ON        `user_phones`.`phone_UserID` = `user_locality`.`UserID`
WHERE     `user_locality`.`CountryCode` = '{$getCountryCode}'

The one thing to point out this query will result in more than 1 row for each user that has more than 1 phone or address.


If I've understood you correctly, something like this should work:

SELECT (fields you want) FROM user_phones, user_addresses, user_locality WHERE user_locality.CountryCode = '{$getCountryCode}' AND user_phones.phone_userID = user_locality.UserID AND user_addresses.address_UserID = user_phones.phone_UserID

In general, the beauty of SQL is that you can specify MULTIPEL tables in the FROM field, thus allowing you to do a join by stating the conditions for keeping a combination of rows in the results. For example, if you do

SELECT * FROM table_a, table_b

You'll get every possible combination of rows. So if A has 10 rows and B has 25, you'll get 250 result rows! Adding WHERE table_a.something = table_b.something will give you what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号