0

I have two mysql tables called users and images. Every user have up to 5 pictures. 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. If the images are 3 returned rows are 3 and so on. 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.

3 Answers 3

0

you could do

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

1
  • which would basically group all user rows into one, and the max(i.uploadDate) should make the row use the details from the last uploaded use min() for the first
    – Hailwood
    Feb 21, 2011 at 9:10
0

You could use a case when clause. I'm not a MySQL person, but you could try something like this:

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
1
  • Thanks, but I`m looking for some more elegant solution.
    – brodo
    Feb 21, 2011 at 9:09
0

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.

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).

$count = mysql_num_rows($result)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.