10

How can I select and don't show duplicates? Actually, it's showing like that: apple | apple | apples | apple

This is my code:

$search = $_GET['q'];
$query = "SELECT * FROM query WHERE searchquery LIKE '%$search%' AND searchquery <> '$search'"; 
MLavoie
  • 9,671
  • 41
  • 36
  • 56
elmaso
  • 193
  • 1
  • 2
  • 14

1 Answers1

23

You already said the magic word: DISTINCT.

SELECT DISTINCT columnname
FROM query
WHERE ....

Note that it probably won't work if you use SELECT DISTINCT * because when you select * that means select all columns, including columns which have a unique constraint such as the primary key. Only select the columns you need - stay away from * in general, and especially so when using DISTINCT.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    4 years later and your answer is still resolving problems. Thanks! – RugerSR9 Jul 03 '14 at 15:42
  • Adding to the answer: you can either use DISTINCT or GROUP BY (all fields selected), of course distinct would be more compact. [This question](https://stackoverflow.com/questions/581521/whats-faster-select-distinct-or-group-by-in-mysql?rq=1) talks a little bit more about this. – zazke May 15 '19 at 04:13