使用 DISTINCT 和 UNION 在 SQL 查询中获取字段名称

发布于 2024-12-19 20:55:02 字数 459 浏览 2 评论 0原文

我有以下查询:

SELECT DISTINCT(uniq)
FROM
(
    SELECT sex AS uniq FROM type4
    UNION
    SELECT fason AS uniq FROM type4
    UNION
    SELECT color AS uniq FROM type4
    UNION
    SELECT size AS uniq FROM type4
) AS Temp

它几乎运行良好,它返回:

[uniq] => some unique value

是否可以知道这个唯一值来自哪一列? 我的意思是这样的:

[uniq] => some unique value
[from] => size

我怎样才能做到这一点?

I have following query:

SELECT DISTINCT(uniq)
FROM
(
    SELECT sex AS uniq FROM type4
    UNION
    SELECT fason AS uniq FROM type4
    UNION
    SELECT color AS uniq FROM type4
    UNION
    SELECT size AS uniq FROM type4
) AS Temp

It works almost well, it returns:

[uniq] => some unique value

Is it possible to know which column this unique value was from?
I mean something like this:

[uniq] => some unique value
[from] => size

How can I do this?

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

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

发布评论

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

评论(2

自在安然 2024-12-26 20:55:02

您的原始查询不需要子查询,也不需要 DISTINCT。您可以使用:

SELECT sex AS uniq FROM type4
UNION
SELECT fason FROM type4
UNION
SELECT color FROM type4
UNION
SELECT size FROM type4

现在对于您的问题,如果四列没有重叠值,您可以使用:

  SELECT DISTINCT sex AS uniq
                , 'sex' AS FromColumn 
  FROM type4
UNION ALL
  SELECT DISTINCT fason 
                , 'fason' 
  FROM type4
UNION ALL
  SELECT DISTINCT color 
                , 'color' 
  FROM type4
UNION ALL
  SELECT DISTINCT size 
                , 'size' 
  FROM type4

Your original query does not need the subquery nor the DISTINCT. You could use:

SELECT sex AS uniq FROM type4
UNION
SELECT fason FROM type4
UNION
SELECT color FROM type4
UNION
SELECT size FROM type4

Now for your question, if the four columns have no overlapping values, you could use:

  SELECT DISTINCT sex AS uniq
                , 'sex' AS FromColumn 
  FROM type4
UNION ALL
  SELECT DISTINCT fason 
                , 'fason' 
  FROM type4
UNION ALL
  SELECT DISTINCT color 
                , 'color' 
  FROM type4
UNION ALL
  SELECT DISTINCT size 
                , 'size' 
  FROM type4
·深蓝 2024-12-26 20:55:02
SELECT DISTINCT(uniq)
FROM
(
    SELECT (sex + ' 1') AS uniq FROM type4
    UNION
    SELECT (fason + ' 2') AS uniq FROM type4
    UNION
    SELECT (color + ' 3') AS uniq FROM type4
    UNION
    SELECT (size + ' 4') AS uniq FROM type4
) AS Temp

然后你可以使用 substring 删除右边的最后 2 个

SELECT DISTINCT(uniq)
FROM
(
    SELECT (sex + ' 1') AS uniq FROM type4
    UNION
    SELECT (fason + ' 2') AS uniq FROM type4
    UNION
    SELECT (color + ' 3') AS uniq FROM type4
    UNION
    SELECT (size + ' 4') AS uniq FROM type4
) AS Temp

then you can use substring to remove the last 2 from right

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