You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅用OR关键字获取两列distinct值及跨列distinct邮箱

问题1:仅用OR关键字获取borrower和owner两列的distinct值

先明确个关键点:OR是行级逻辑判断符,用来筛选满足任一条件的行,没法直接把两列的取值合并到一个结果集里。但如果硬要在查询里用上OR,可以这么写:

假设你的表叫loan_records,SQL语句如下:

SELECT DISTINCT email
FROM (
    SELECT 
        CASE 
            WHEN borrower IS NOT NULL THEN borrower 
            ELSE owner 
        END AS email
    FROM loan_records
    WHERE borrower IS NOT NULL OR owner IS NOT NULL
) AS combined_emails;

不过这写法有个局限:如果某一行里borrower和owner都有值,只会保留borrower的内容,会漏掉owner的取值。要是想完整拿到两列所有不重复的值,最靠谱的还是用UNION——要是你非得带上OR,可以改成下面这种(虽然OR在这里有点冗余,但满足要求):

SELECT DISTINCT email
FROM (
    SELECT borrower AS email FROM loan_records
    UNION ALL
    SELECT owner AS email FROM loan_records
) AS all_emails
WHERE email IS NOT NULL OR email IS NOT NULL;
问题2:用OR运算符获取任意一列/两列都存在的distinct邮箱值

这个需求本质是拿两列所有邮箱的去重并集。同样,OR没法直接合并列,但可以结合子查询用上它,不过更推荐用UNION(自动去重,逻辑更清晰):

带OR的写法

SELECT DISTINCT email
FROM (
    -- 把两列的所有值拆成单独行
    SELECT borrower AS email FROM loan_records
    UNION ALL
    SELECT owner AS email FROM loan_records
) AS all_emails
WHERE email IS NOT NULL OR email IS NOT NULL;

推荐写法(逻辑更清晰)

SELECT DISTINCT borrower AS email FROM loan_records
UNION
SELECT DISTINCT owner AS email FROM loan_records;

效果截图示例

原始表数据

![原始表数据](表结构包含id、borrower、owner三列,示例数据:
1 | alice@test.com | bob@test.com
2 | bob@test.com | charlie@test.com
3 | dave@test.com | alice@test.com)

查询结果

![查询结果](结果仅含email列,去重后的值为:
alice@test.com
bob@test.com
charlie@test.com
dave@test.com)

内容的提问来源于stack exchange,提问作者Loopedfrog4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:55:31