开发者

Joining 3 three tables

开发者 https://www.devze.com 2023-02-18 20:59 出处:网络
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:

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:

Joining 3 three tables

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']; ?&g开发者_开发问答t; 
AlbumID: <?php echo $row['album_id']; ?>


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


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


@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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消