¿Cómo SELECCIONAR con un LÍMITE mientras se necesitan varias filas con un mismo valor de columna?

I have the following table as an example.

id uid car 
1  3   BMW
2  3   AUDI
3  3   JEEP
4  5   MERC
5  6   BMW
6  6   FIAT

Now, I would like to get all cars but for only 2 users but don't know how many cars they have. When they all would have had only one car, I could just do a LIMIT 3 but how can I do this to get all the cars, but only for 2 users?

preguntado el 02 de febrero de 12 a las 10:02

can you elaborate more on what you are trying to accomplish?? -

@KamranAli What I'm after is to get a list of users (with jQuery) that at first, shows only one car for each user. If you click on the user, you get to see all his cars. I can do this with multiple queries, but would rather have this all in one. (PS, the real application is a bit to complicated to explain, so I use the cars as an example) -

@ajreal how would that work? I never used GROUP_CONCAT before. -

I think this can be done on the front end rather on the SQL side, you can simply fetch all the rows and than show/hide them using jquery on the front end. -

True, but I like to show in the first row how many cars someone has (like: See all his 3 cars). So I will need that data upfront. Could this be done in one SQL query? -

1 Respuestas

EDITAR

If the 2 users are unknown you can use MySQL GROUP_CONCAT

$query = mysql_query("SELECT uid, GROUP_CONCAT(car) as cars FROM tablename GROUP BY uid ORDER BY uid ASC LIMIT 0,2");
while ($get = mysql_fetch_array($query)) {
  $userid = $get['uid'];
  $result = explode(",", $get['cars']);
  echo '<h2>User #' . $userid . ' owns the following cars:</h2>' . "\n";
  echo '<ul>' . "\n";
  foreach ($result as $car) {
    echo '  <li>' . $car . '</li>' . "\n";
  }
  echo '</ul>' . "\n";
}

Note: Don't forget to change the tablename in the SELECT query

Respondido 02 Feb 12, 15:02

Thanks, but this is not a solution because I don't know the users on forhand. - Glooh

@Glooh - Ok! Just updated my answer. Should be exactly what you're looking for :) - tom

Great! Exactly what I need! I tested it and can do some extra stuff on the frontend, but at least I have one query now. Thanks!! - Glooh

@Glooh - Great! No problem. Glad I could help :) - tom

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.