简体   繁体   中英

Only get one occurance of a table row in mysql php based on id

I have a table that looks like this

id            |            itemID        |         catID     |      Title
----------------------------------------------------------------------------
0                           3                       4                Hello
1                           3                       6                Hello
2                           4                       4                Yo
3                           4                       8                Yo
4                           5                       2                Hi
5                           1                       3                What

I want to do a MySQL PHP Select that only gets one occurrence of the itemID. As you can see they are the same item, just in different categories.

This is what I tried

SELECT * FROM Table GROUP BY itemID

That didn't seem to work, it still just shows duplicates.

Is this what you are looking for? http://www.sqlfiddle.com/#!2/5ba87/1

select itemID, Title from test group by itemID;

As far as MySQL is concerned, the data is all unique, since you want all of the columns. You have to be more specific.

Do you just want the itemID (or other column)? Then say so:

select [column] from Table GROUP BY itemID

Do you want the last entry of a particular item ID? Then say that:

select * from Table where itemID = 1 ORDER BY id DESC

Or the first one?

select * from Table where itemID = 1 ORDER BY id

If none of these are what you want, then you probably need to restructure your tables. It looks like you want different categories for your items. If so, then you'll want to split them out into a new join table, because you have a many-to-many relationship between Items and Categories. I recommend reading up on database normalization, so you're not duplicating data (such as you are with the titles).

If you want everything for the distinct itemIDs, you could certainly take a long route by doing one selection of all of the distinct itemIDs, then doing a series of selections based on the first query's results.

select distinct(`itemID`) from Table

Then in your PHP code, do something like this:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
    $itemID = $row['itemID'];

    $sql2 ="SELECT * FROM Table WHERE 1 and `itemID`=\"$itemID\" limit 1";
    $result2 = @mysql_query($sql2, $connection);
    while ($row2 = mysql_fetch_array($result2))     
        {
            $id = $row2['id'];
            $itemID = $row2['itemID'];
            $catID = $row2['catID'];
            $Title = $row2['Title'];
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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