0

I have a MySQL Database with hundreds of items identified by 2 different values: model and color.

Ex:

model | color
------|------
  001 | 1
  001 | 1
  001 | 2
  004 | 1
  004 | 2

I'm printing a table of all different avaliable items with a php script where identical items should be skipped. The output should be something like this:

model | color
------|------
  001 | 1
  001 | 2
  004 | 1
  004 | 2

Notice that the item model: 001, color:1 should only be displayed once.

What is the best way to get the job done ? I was considering adding a string of model:color to a array $listed after each item is added and then check with in_array() if the item was already listed. Is this a acceptable approach or is there a less dummy solution ?

PS: There are other values to be retrieved from the database to display on the table, such as 'name', 'value', 'size'. I'm not sure how that will make a difference.

If you'll make sugestions please leave some code as example.

Many thanks!

bockzior
  • 199
  • 1
  • 6
  • 20
  • 3
    Maybe this is helpful? http://stackoverflow.com/questions/1330692/distinct-pair-of-values-sql Or this http://stackoverflow.com/questions/12013900/selecting-distinct-pair-mysql – Dan Mar 04 '14 at 22:22
  • Looks close to what I want but there are other values to be retrieved from the database to display on the table, such as 'name', 'value', 'size'. I'm not sure how that will make a difference. – bockzior Mar 04 '14 at 22:29
  • Can you do it from MYSQL side? e.g. SELECT DISTINCT model, color FROM table; – VVLeon Mar 04 '14 at 22:42
  • I can and now knowing that is possible I prefer it, but I still need to select all the columns for each item and one of them 'unique_id' is different on every single item. – bockzior Mar 04 '14 at 22:52
  • Show us the various ways, and we'll tell you which one is best – Strawberry Mar 04 '14 at 23:16
  • `SELECT DISTINCT...` OR `GROUP BY...` – Jack Mar 05 '14 at 03:37

2 Answers2

3

If you can't use group/distinct, then your solution is acceptable. However, I usually like to do isset instead of in_array:

$completed = array();
foreach ($rows as $data) {
    $key = $data['model'] . $data['color'];
    if (isset($completed[$key])) {
        continue;
    }
    // Display
    $completed[$key] = true;
}

The reason being that I usually have to work with large sets and doing isset is generally faster than having to do in_array for thousands of items.

Aziz Saleh
  • 2,687
  • 1
  • 17
  • 27
0

Solved it with:

SELECT * from table_name GROUP BY model, color
bockzior
  • 199
  • 1
  • 6
  • 20