我正在使用innodb是id_name->的外键name.id和id_street-> street.id 我希望从名称表中获取名称和号码,具体取决于街道&使用关系表从街道表拉链但我不知道我应该使用的SQL查询。
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 |
我应该使用多个查询:
- 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)
或者可以合并所有查询。
答案 0 :(得分:2)
使用此查询:
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";
答案 1 :(得分:0)
您可以通过应用多个连接来实现结果
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)
您可以添加更多自定义条件来过滤并通过别名选择所需的列