简体   繁体   中英

Unique/Distinct values from a PHP/MYSQL query

I have a database with the fields type1 , type2 , type3 , type4 all the way up to type19 , along with other fields. What I am trying to do is to get all the fields from those rows and then only echo the fields which are not duplicates.

I have tried using select distinct type1, type2 etc from products but do not know the php code to put all the fields ( $_row['type1'] $_row['type2'] etc) into a single variable and then echo all the distinct values from that variable. Does anyone have any suggestions?

If you wanted to use an SQL query only, you can say

SELECT DISTINCT type1 FROM products ORDER BY type1 

An alternative is

SELECT type1, max(1) FROM products GROUP BY type1 

The downside is that you have to do 19 queries if you want to get distinct values for all of your columns.

The upside is that if you want distinct values for one column, it's a lot easier.

You could batch the 19 queries into a for loop, perhaps:

for($i=1;$i<20;$i++) {
  $sql = "SELECT DISTINCT type".$i." FROM products ORDER BY type1";
  // Run the sql query to get the data, then manipulate it as you wish.
}

Loop through your results and add them to an array. Then use array_unique() to return only unique values.

http://php.net/manual/en/function.array-unique.php

You should definitely rethink your database design if possible however, since this is a pretty bad way to do things.

Use UNION to join the results of 19 queries as a subquery.

SELECT DISTINCT a FROM (
  SELECT DISTINCT type1 AS a FROM products
  UNION
  SELECT DISTINCT type2 AS a FROM products
  UNION 
  ...
  SELECT DISTINCT type19 AS a FROM products
) ORDER BY a

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