简体   繁体   English

来自 PHP/MYSQL 查询的唯一/不同值

[英]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.我有一个数据库,其中包含字段type1type2type3type4一直到type19以及其他字段。 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.我曾尝试使用select distinct type1, type2 etc from products但不知道 php 代码将所有字段( $_row['type1'] $_row['type2']等)放入单个变量,然后回显所有与该变量不同的值。 Does anyone have any suggestions?有没有人有什么建议?

If you wanted to use an SQL query only, you can say如果您只想使用 SQL 查询,您可以说

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.不利的一面是,如果要为所有列获取不同的值,则必须执行 19 次查询。

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:您可以将 19 个查询批处理到一个for循环中,也许:

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.然后使用 array_unique() 仅返回唯一值。

http://php.net/manual/en/function.array-unique.php 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.使用 UNION 将 19 个查询的结果连接为子查询。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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