简体   繁体   English

在mysql查询中限制结果

[英]Limit results in mysql query

I have two mysql tables called users and images. 我有两个名为用户和图像的mysql表。 Every user have up to 5 pictures. 每个用户最多可以拥有5张图片。 In a page I show users information plus one image (first uploaded). 在一个页面中,我显示用户信息以及一张图像(首先上传)。 When I do query like this 当我这样查询时

SELECT
  SQL_CALC_FOUND_ROWS,
  u.username,
  u.gender,
  u.etc
  .........
  i.picture
FROM users u
LEFT JOIN images i on u.id = i.id
WHERE 
 some_condition

and if the user has two uploaded images mysql result is 2 rows. 如果用户有两个上载的图像,则mysql结果为2行。 If the images are 3 returned rows are 3 and so on. 如果图像是3,则返回的行是3,依此类推。 How to do so the result to be just one row (one pictue) ? 如何做的结果只是一排(一皮克)?

I tried to add LIMIT 0, 1 but SQL_CALC_FOUND_ROWS returns the actual number of pictures. 我尝试添加LIMIT 0、1,但SQL_CALC_FOUND_ROWS返回实际的图片数量。

You could use a case when clause. 您可以使用case when子句。 I'm not a MySQL person, but you could try something like this: 我不是MySQL使用者,但您可以尝试执行以下操作:

SELECT
  case 
    when SQL_CALC_FOUND_ROWS > 5 then '5'
    else SQL_CALC_FOUND_ROWS
  end,
  u.username,
  u.gender,
  u.etc
  .........
  i.picture
FROM users u
LEFT JOIN images i on u.id = i.id
WHERE 
 some_condition

SQL_CALC_FOUND_ROWS will return the number of rows in the full result set, whereas a LIMIT statement tells the query to only return a limited number of rows from that result set. SQL_CALC_FOUND_ROWS将返回整个结果集中的行数,而LIMIT语句告诉查询仅从结果集中返回有限的行数。

I don't see why you need to use SQL_CALC_FOUND_ROWS at all here, you can just count the number of rows in the last result set (and use a LIMIT). 我不明白为什么这里根本不需要使用SQL_CALC_FOUND_ROWS,您可以只计算最后一个结果集中的行数(并使用LIMIT)。

$count = mysql_num_rows($result)

你可以做

select max(i.uploadDate) group by (u.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM