Mysql-联接-返回的行太多-每个联接表一行,但不希望这样
我有这种mysql数据库(表名/字段) 待定用户:id、标题、已批准 tbl_照片:id、用户id、标题、文件名 我有一行用户和三张照片(都有用户的id=用户的id) 这样做:Mysql-联接-返回的行太多-每个联接表一行,但不希望这样,mysql,sql,database,mysql5,Mysql,Sql,Database,Mysql5,我有这种mysql数据库(表名/字段) 待定用户:id、标题、已批准 tbl_照片:id、用户id、标题、文件名 我有一行用户和三张照片(都有用户的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()
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的用户id的随机照片)
我尝试了所有连接-左-右-内,但它们总是返回3行您的代码应该如下所示
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行的查询
我的sql命令示例的简单列表可以在这里找到
您还添加了
不同的:
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()
如果您只想为每一行获取一行,那么这样做非常简单
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()
它将在单个字段中为您提供逗号分隔的值如果文件名是您将从tbl_照片中检索的唯一字段,这可以提供您所需要的:
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
)
在这个示例中,我只有一个用户,但我希望返回所有用户,每个用户都有一张随机照片(如果存在)。添加limit 1会将整个查询限制为one@notsid:如果您希望每个用户有一行(一张照片),则应在问题中添加该行。我们没有通灵能力。你用单引号括起来Approved
?它是一个字符串,所以你需要将它括起来。是的,我说的“它不工作”是指它仍然返回3个结果,而不是sql错误如果你删除where条件,你将获得所有用户。与每个用户一起,您将获得与每个用户相关的照片