Joining 3 three tables

不问归期 提交于 2019-12-07 10:51:03

问题


I have this diagram which should explain my situation I need some help on joining 3 tables which I have no idea how to do this kind of thing:

So I can go through a while loop of retrieving the records by doing this:

<img src="<?php echo $row['filename']; ?>" alt="" />

Album: <?php echo $row['album_name']; ?> 
AlbumID: <?php echo $row['album_id']; ?>

回答1:


Using an INNER JOIN will prevent returning albums that don't have images. The ORDER BY ... DESC will sort the results in descending order but I'm not sure how to only return the last record. It would take some sort of combination of ORDER BY, GROUP BY and TOP, perhaps.

SELECT 
    album_table.album_id, 
    album_table.album_name, 
    images_table.filename
FROM album_table
INNER JOIN images_table ON images_table.album_id = album_table.album_id
WHERE album_table.user_id = uid
ORDER BY images_table.date DESC



回答2:


I believe an INNER JOIN is what you are looking for

This site gives a good example

http://www.w3schools.com/sql/sql_join_inner.asp




回答3:


@lolwut: Try --

SELECT 
  album_table.album_id, album_table.album_name, images_table.filename 
FROM album_table 
  INNER JOIN images_table ON images_table.album_id = album_table.album_id
  INNER JOIN users_table ON users_table.uid = album_table.user_id
WHERE (users_table.uid = ' . $uid . ') 
ORDER BY images_table.date DESC

$uid should be the currently logged in user's session...or you can leave that WHERE clause out entirely if you want to return all users' info.




回答4:


Actually, in this case you only need to join two tables (as a general rule of thumb, the fewer joins you do, the better).

Since you know the User ID, you can query that directly off of the album table name.

If your users_table happened to have another column "user_name", and you wanted to search of that, then you would need to join to the users table.

SELECT filename, album_name, album_id
FROM album_table at, images_table it
AND at.album_id = it.album_id
AND at.user_id = $user_id


来源:https://stackoverflow.com/questions/5396717/joining-3-three-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!