简体   繁体   中英

Fetching results when using the same table twice

I'm trying to fetch the results of a query where I've joined the same table twice, but I can't seem to figure out how to get the results. How do I select the correct version of the table?

I am creating a vacation system where users can request dates to take time off of work, and have another user accept or deny it. So I'm joining the user table twice to show who's requested it, and who's handled the request.

I can get the results in MySQL and it lists everything, but the code to get the results using ASP Classic doesn't seem to work.

This is my SQL query and code to fetch the data:

sql = "SELECT * FROM vacation LEFT JOIN user ua ON vacation_user = ua.user_id LEFT JOIN user ub ON vacation_granted_id = ub.user_id WHERE 1"
Set RS = Cn.Execute(sql)

uname = RS("ua.user_name")
gname = RS("ub.user_name")

I was hoping I could get the values from the user table using "ua." and "ub." to fetch the correct table, but that returns nothing.

Is it simply not possible using "SELECT *"? Do I have to declare all variables up front to be able to use the same table twice?

You need to provide separate alias names for each:

SELECT v.*, u.user_name, ug.user_name as granted_user_name
FROM vacation v LEFT JOIN
     user u
     ON v.vacation_user = u.user_id LEFT JOIN
     user ug
     ON v.vacation_granted_id = ug.user_id ;

And then, of course, fetch them using the names:

uname = RS("user_name")
gname = RS("granted_user_name")

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