我有这种mysql db(表名/字段)
tbl_users :id,title,approved
tbl_photos :id,user_id,title,filename
我在用户中有一行,有三张照片(所有用户都是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行
答案 0 :(得分: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行。
可以在此处找到my-sql命令示例的简单列表 http://itswadesh.wordpress.com/2011/04/12/mysql-commands/
答案 1 :(得分: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()
答案 2 :(得分: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()
它会在单个字段中为您提供逗号分隔值
答案 3 :(得分:0)
如果文件名是您将从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
)