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

发布于 2024-11-25 04:40:01 字数 313 浏览 0 评论 0原文

我有一个数据库,其中字段 type1type2type3type4 一直到 type19 以及其他字段。我想做的是从这些行中获取所有字段,然后仅回显不重复的字段。

我尝试使用从产品中选择不同的type1、type2等,但不知道放置所有字段的php代码($_row['type1'] $ _row['type2'] 等)到单个变量中,然后回显该变量中的所有不同值。有人有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七颜 2024-12-02 04:40:01

循环遍历结果并将它们添加到数组中。然后使用 array_unique() 仅返回唯一值。

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

但是,如果可能的话,您绝对应该重新考虑您的数据库设计,因为这是一种非常糟糕的做法。

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.

柒七 2024-12-02 04:40:01

如果您只想使用 SQL 查询,您可以说

SELECT DISTINCT type1 FROM products ORDER BY type1 

另一种选择是

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

缺点是,如果您想获取所有列的不同值,则必须执行 19 次查询。

好处是,如果您希望一列具有不同的值,那么会容易得多。

您可以将 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.
}

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.
}
稳稳的幸福 2024-12-02 04:40:01

使用 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文