选择已加入的行

时间:2011-03-17 03:08:41

标签: php mysql

如果我有这两行:

Users Table      UserId  |  Username  |  Etc...
                 5       |  John      |

Avatars Table    Id      |  UserId    |  ImageName         |  ImageType
                 1       |  5         |  example.png       |  original
                 2       |  5         |  example_thumb.png |  thumbnail

我有:

SELECT * FROM Users JOIN Avatars 
ON Users.UserId=Avatars.UserId WHERE Users.UserId = '5'

我是否必须添加其他内容:

AND Avatars.ImageType = 'thumbnail'

或者有没有办法选择所有并获得我想要的PHP(很像一个数组:$ var ['something'])??

或者是否可以使用类似'AS'子句的东西来区分它们?

4 个答案:

答案 0 :(得分:2)

如果没有进一步限定ImageType条件的连接,您将获得每个用户记录多行。

编辑例如

SELECT u.UserId, u.Username, a.ImageName, a.ImageType
FROM Users u
INNER JOIN Avatars a ON u.UserId = a.UserId
WHERE u.UserId = 5

UserId    Username    ImageName            ImageType
----------------------------------------------------
5         John        example.png          original
5         John        example_thumb.png    thumbnail

编辑#2:如果您想要将这两个图片放在一行中,请使用此查询

SELECT u.UserId, u.Username,
    orig.ImageName as OriginalImage, thumb.ImageName as ThumbImage
FROM Users u
INNER JOIN Avatars orig ON u.UserId = orig.UserId
    AND orig.ImageType = 'original'
INNER JOIN Avatars thumb ON u.UserId = thumb.UserId
    AND thumb.ImageType = 'thumbnail'
WHERE u.UserId = 5

请注意,这只会返回Avatars中用户同时存在两种图像类型的行。如果您想获得结果而不管是否存在头像图像,请使用左连接。

答案 1 :(得分:2)

如果您只有两种图像尺寸,则可以

SELECT 
    Users.UserId, 
    AvatarsThumbnails.ImageName AS ThumbnailImageName, 
    AvatarsOriginals.ImageName AS OriginalImageName  
FROM Users 
LEFT JOIN Avatars AS AvatarsThumbnails 
    ON Users.UserId=AvatarThumbnails.UserId AND AvatarThumbnails.ImageType='thumbnail' 
LEFT JOIN Avatars As AvatarsOriginals
    ON Users.UserId=AvatarsOriginals.UserId AND AvatarOriginals.ImageType='original'
WHERE Users.UserId = '5' 

答案 2 :(得分:2)

SELECT Users.*, O.ImageName as OriginalImage, T.ImageName as Thumbnail
FROM Users
LEFT JOIN Avatars O ON Users.UserId=O.UserId AND T.ImageType = 'original'
LEFT JOIN Avatars T ON Users.UserId=T.UserId and T.ImageType = 'thumbnail'
WHERE Users.UserId = '5'

使用LEFT JOIN,这样如果缺少原始缩略图或缩略图,则仍会检索另一个。如果两者都丢失了,你仍然会得到一条记录,但两者都是NULL。

答案 3 :(得分:1)

即使有一种方法可以在PHP中执行此操作,我强烈建议让MySQL进行过滤(通过执行“AND ...”)。MySQL是为完成此类任务而构建的。