i'm using innodb is foreign key for id_name-> name.id and id_street-> street.id and i would like to get the name&number from name table depending on the street & zip from street table using the relationship table but i don't know the sql query i should use.
Name Street Relationship
___________ _______ ______________ ____ __________________________
|id |name | number| |id | street |zip | |id | id_name | id_street |
|____|_____|_______| |____|________|____| |___|_____________________|
|1 | aaa | 11111 | |1 | s1 |600 | |1 | 1 | 1 |
|2 | bbb | 11112 | |2 | s2 |600 | |2 | 1 | 2 |
|3 | ccc | 11113 | |3 | s3 |600 | |3 | 2 | 3 |
should i use multiple query :
- 1)get the id of the street/zip (ex: s2 and 600 return=2 )
- 2)get the id of the name (1) from the returned id (2)
- 3) select name/number field from name id (1)
or it's possible to merge all the queries.
Use this query:
SELECT name.name, name.number FROM name
JOIN relationship AS r ON name .id = r.id_name
JOIN street ON street.id = r.id_street
WHERE street.street = "yourStreet" AND street.zip="1111";
You can achieve the results by applying multiple joins
SELECT
N.name,n.number
FROM
Name N,
Street S,
Relationship R
WHERE
N.id = R.id_name
AND
S.id = R.id_street
AND
R.id_street = 2 (Displays data only Street ID 2)
you can add more custom conditions to filter and select the required columns thru aliases
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.