简体   繁体   中英

php, mysql join table columns with another table rows

I have issue getting results from two database table. here is what i have:

table A: 'courses' 

math  | history  | geography  | computer 
1     | 2        | 3          | 4 

and Table B

user_id | classroom_id | course 
1       | 5            | 3
1       | 5            | 4
1       | 6            | 2

I returned the table A on a for each loop but I would like to check what courses the user 1 has to return true or false on any Table a columns. Any help appreciated. I need help not negative votes :(

You have your database set up wrong I believe. What you want is something like

Table_A:
PKEY |    Course

1    |    Math
2    |    History
3    |    Geography
4    |    Computer



Table_B:
user_id | classroom_id | course 
1       | 5            | 3
1       | 5            | 4
1       | 6            | 2

Then you could do something like

SELECT 
TableA.PKEY,
TableA.Course,
TableB.user_id,
TableB.classroom_id,
TableB.course,
FROM TableA
LEFT JOIN TableB
ON TableA.PKEY = TableB.course

^^This will return the data from BOTH tables.

you see this line

ON TableA.PKEY = TableB.course

                    ^^This is called the foreign key.

BIG GOTCHA: Make SURE that the columns for both of those ^^^ are set up EXACTLY the same. For instance, IF TableA.PKEY is an UNSIGNED INT(10), then TableB.course MUST also be UNSIGNED INT(10). They have to be identical for the join to work correctly.

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