0

我有这种mysql db(表名/字段)

tbl_users : id、title、已批准

tbl_photos : id、user_id、标题、文件名

我在用户中有一行,三张照片(全部带有 user_id = 用户的 id)

这样做:

select 
tbl_users.*, 
tbl_photos.filename 

from tbl_users 

left join tbl_photos on tbl_photos.user_id = tbl_users.id 

where tbl_users = '1' order by rand() 

(表查询简化了一点)

执行该 sql 查询返回三行。我只想要一行(即我想要用户行,加上任何具有该用户 ID 的 user_id 的随机照片)

我已经尝试了所有连接 - 左右内连接,但它们总是返回 3 行

4

4 回答 4

2

您的代码应如下所示

select 
tbl_users.*, 
tbl_photos.filename 

from tbl_users 

left join tbl_photos on tbl_photos.user_id = tbl_users.id 

where tbl_users = approved order by rand() LIMIT 1

LIMIT 关键字将限制查询只返回 1 行。

可以在这里找到一个简单的 mysql 命令示例列表 http://itswadesh.wordpress.com/2011/04/12/mysql-commands/

于 2012-05-04T03:33:34.563 回答
0

如果您只想为每行获取一行,这非常简单

select 
tbl_users.*, 
GROUP_CONCAT(tbl_photos.filename) as Photos

from tbl_users 

left join tbl_photos on tbl_photos.user_id = tbl_users.id 

where tbl_users = '1' order by rand() 

它将在单个字段中为您提供逗号分隔值

于 2012-05-04T05:47:47.973 回答
0

如果 filename 是您将从 tbl_photos 检索的唯一字段,这可以提供您需要的内容:

select 
    tbl_users.*, 

    (select filename 
     from tbl_photos where user_id = tbl_users.id 
     order by rand()
     limit 1) as filename

from tbl_users 

如果您想从照片中获取其他信息,请执行以下查询:

select tbl_users.*, 'x' as separator, tbl_photos.*
from tbl_users
left join tbl_photos on tbl_photos.user_id = tbl_users.id
where (tbl_users.id, tbl_photos.id) in

    (  
    -- you can run this query independently
        select 

            id, 

            (select id 
             from tbl_photos 
             where user_id = tbl_users.id 
             order by rand() 
             limit 1) 

        from tbl_users
    )
于 2012-05-04T06:06:20.560 回答
0

您还添加DISTINCT

select  DISTINCT tbl_users.id, 
        tbl_users.title, 
        tbl_users.approved, 
        tbl_photos.filename 
from tbl_users left join tbl_photos 
       on tbl_photos.user_id = tbl_users.id 
where tbl_users = 'approved' order by rand() 
于 2012-05-04T03:39:35.273 回答