Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT query, LIMIT 1 for one column, but, not the rest

Tags:

php

mysql

Can I LIMIT 1 for one specific column but not the rest? I have two tables. One with info and one with images. For as many images there are, that many info queries are run. So, it will be 5 images and 5 of the same title. How can I LIMIT 1 title, and LIMIT 3 images?

$query = mysql_query("
                     SELECT `$category`.title AS title,
                     page_images.image_loc AS images
                     FROM `$category`, page_images
                     WHERE `$category`.title = page_images.title
                    ");

            while($fetch = mysql_fetch_assoc($query)) {

                $title  = $fetch['title'];              
                $images = $fetch['images'];

                echo '<b>'.$title.'</b><br />';
                echo '<a href="http://localhost/'.$images.'">
                        <img src="http://localhost/'.$images.'" height="80" width="80" />
                      </a>';

                }
like image 893
Graham Avatar asked Nov 18 '11 05:11

Graham


People also ask

How do I limit one column in SQL?

EDIT: For SQL Server, replace LIMIT @num with TOP @num before the UNION ALL in each query and replace the DEFAULT with = . You can also have a second line to declare the @num as a string and use the PERCENT keyword, but only in SQL Server as neither MySQL nor Oracle supports it.

How do you select only the first rows for each unique value of a column in SQL?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on.

How do I select distinct from one column in SQL?

Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set. Since DISTINCT operates on all of the fields in SELECT's column list, it can't be applied to an individual field that are part of a larger group.


1 Answers

you can group by title and collect image locations using GROUP_CONCAT. and then you can explode the collected locations to an array. and print all the images.

here what i mean

$query = mysql_query( "
SELECT
     title AS title
    ,GROUP_CONCAT( i.image_loc ) AS images
FROM
    `$category` c
    JOIN page_images i USING( title )
GROUP BY
    title
" );

while( $fetch = mysql_fetch_assoc( $query ) ) {
    $title  = $fetch[ 'title' ];              
    $images = explode( ',', $fetch[ 'images' ] );

    echo '<b>' . $title . '</b><br />';
    foreach( $images as $image ) {
        echo '<a href="http://localhost/'.$image.'">
            <img src="http://localhost/'.$image.'" height="80" width="80" />
        </a>';
    }
}
like image 99
ncank Avatar answered Sep 21 '22 18:09

ncank