简体   繁体   English

使用where语句在多个列上选择不重复

[英]Select distinct on multiple columns with where statement

I want to select each available entry for each column once. 我想为每列选择一次可用的条目。 This problem was solved with 这个问题解决了

SELECT DISTINCT a from my_table
UNION
SELECT DISTINCT b from my_table
UNION
SELECT DISTINCT c from my_table
UNION
SELECT DISTINCT d from my_table

in this question: MySQL SELECT DISTINCT multiple columns 在此问题中: MySQL SELECT DISTINCT多列

I want to go further and use the same WHERE statements on each subquery. 我想走得更远,在每个子查询上使用相同的 WHERE语句。 Is there any way without defining the WHERE each time? 有没有不用每次都定义WHERE方法吗? My current query would look like this: 我当前的查询如下所示:

SELECT DISTINCT a from my_table WHERE a='a' AND b=1 AND c='.' AND d='ab'
UNION
SELECT DISTINCT b from my_table WHERE a='a' AND b=1 AND c='.' AND d='ab'
UNION
SELECT DISTINCT c from my_table WHERE a='a' AND b=1 AND c='.' AND d='ab'
UNION
SELECT DISTINCT d from my_table WHERE a='a' AND b=1 AND c='.' AND d='ab'

All parameters don't have to be given, I just want to show the maximum that has to be possible. 不必给出所有参数,我只想显示必须达到的最大值。 Is there any way to write this shorter? 有什么办法可以写得更短吗?

I use PHP with doctrine, if that is any help. 如果有帮助的话,我会在理论上使用PHP。

Thanks in advance! 提前致谢!

Example: my_table: 示例:my_table:

  a  |  b  |  c  |  d  
-----+-----+-----+-----
  a  |  0  |  .  | ab
  b  |  0  |  -  | ag
  a  |  1  |  .  | cfd
  c  |  1  |  .  | b
  a  |  1  |  -  | ab
  c  |  1  |  -  | cfd

should give this result (without where statement): 应该给出这个结果(没有where语句):

  a  |  b  |  c  |  d  
-----+-----+-----+-----
  a  |  0  |  .  | ab
  b  |  1  |  -  | ag
  c  |     |     | cfd
     |     |     |  b

And with WHERE b=0 statement: 并使用WHERE b=0语句:

  a  |  b  |  c  |  d  
-----+-----+-----+-----
  a  |  0  |  .  | ab
  b  |     |  -  | ag

EDIT: changed subqueries to UNION and made the data types fit to the example 编辑:将子查询更改为UNION,并使数据类型适合该示例

UPDATE: Well, I originally wrote up a generic SQL solution for this problem, not realizing that MySQL apparently doesn't allow for it. 更新:嗯,我最初为这个问题写了一个通用的SQL解决方案,但没有意识到MySQL显然不允许这样做。

So if you can create a view, that may be the lightest-weight solution. 因此,如果您可以创建视图,那可能是最轻巧的解决方案。 (The view's defining query would be the same as the select in my original solution's with clause.) (视图的定义查询将与原始解决方案的with子句中的select相同。)

Alternately you could create a temporary table. 或者,您可以创建一个临时表。 Maybe a little more resource-intensive if there's much data, but less likely that anyone would restrict the required permissions. 如果有大量数据,则可能会占用更多的资源,但很少有人会限制所需的权限。

For the record, original solution was as follows: 记录下来,原始解决方案如下:

with my_filtered as (
    select *
      from my_table
     where a = 1 and b = 2 -- and ...
)
-- carry on with your query, using my_filtered instead of my_table

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

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