简体   繁体   English

创建两个联接到同一个表

[英]Creating Two joins to same table

From Scheduled I need to make two joins to country, two joins to state and two joins to city. 根据计划,我需要对国家进行两次联接,对州进行两次联接,对城市进行两次联接。

My Tables

Schedule
Destination Country ID  
Destination City ID
Destination State ID
Current Country ID
Current City ID
Current State ID
-------------------
Country
ID
Country
-------------------
State
ID
Statename
Countryid
-------------------
City
ID
City
Stateid
Countryid

I need to read the data from schedule table and list it using the country, state and city names, which are stored in the country, state and city tables, and linked by the ID fields. 我需要从时间表表中读取数据,并使用存储在国家,州和城市表中并由ID字段链接的国家,州和城市名列出它。 I have the first join to each table working, but when I try to second the query fails saying “ Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given ”. 我有第一个连接到每个工作表,但当我尝试第二个查询失败时,说“ Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given ”。

What works… 什么有效...

$query="SELECT schedule.username, schedule.ret, country.country, state.statename, city.city, schedule.business, schedule.pleasure 
FROM schedule 
JOIN country 
ON schedule.dest_country=country.id
JOIN state
ON schedule.dest_state=state.id
JOIN city
ON schedule.dest_city=city.id";

What does not... 什么不...

$query="SELECT schedule.username, schedule.ret, country.country, state.statename, city.city, schedule.business, schedule.pleasure, country.country 
FROM schedule 
JOIN country 
ON schedule.dest_country=country.id
JOIN state
ON schedule.dest_state=state.id
JOIN city
ON schedule.dest_city=city.id
JOIN country 
ON schedule.cur_country=country.id";

Thanks 谢谢

Use aliases on your join tables to separate the duplicate table joins: 在联接表上使用别名来分隔重复的表联接:

$query="SELECT schedule.username, schedule.ret, destcountry.country, state.statename,          city.city, schedule.business, schedule.pleasure, curcountry.country  
FROM schedule 
JOIN country destcountry
ON schedule.dest_country=destcountry.id
JOIN state
ON schedule.dest_state=state.id
JOIN city
ON schedule.dest_city=city.id
JOIN country curcountry
ON schedule.cur_country=curcountry.id";

And to clarify the result set you can name your resulting columns: 为了澄清结果集,您可以命名结果列:

$query="SELECT schedule.username, schedule.ret, destcountry.country as destcountry, state.statename, city.city, schedule.business, schedule.pleasure, curcountry.country as currentcountry

try this SQL bro! 试试这个SQL兄弟!

$query="SELECT * FROM schedule SC
LEFT JOIN country C ON C.id = SC.dest_country
LEFT JOIN state ST ON ST.id = SC.dest_state
LEFT JOIN city Ci ON Ci.id = SC.dest_city
LEFT JOIN country C2 ON C2.id = SC.cur_country";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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