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

MySQL新手求助:合并同表两行并优化DISTINCT查询输出

Hey there! Let's tackle your two MySQL questions one by one, starting with the specific query issue you're facing since you provided sample data.

1. 获取关联ID的单列结果

Your current query returns pairs of IDs where 213 is either the sender or receiver, but you want just the unique associated ID in a single column. Here are two straightforward solutions:

Method 1: Use a CASE statement to pick the non-213 ID

This checks each row and selects the ID that isn't 213, then uses DISTINCT to ensure uniqueness:

SELECT DISTINCT 
    CASE 
        WHEN uid != 213 THEN uid 
        ELSE r_uid 
    END AS `new id`
FROM messenger
WHERE uid = 213 OR r_uid = 213;

Method 2: Combine results with UNION and filter out 213

This approach first fetches all receiver IDs where 213 is the sender, then all sender IDs where 213 is the receiver, combines them, removes duplicates, and excludes 213 itself:

SELECT DISTINCT id AS `new id`
FROM (
    SELECT r_uid AS id FROM messenger WHERE uid = 213
    UNION ALL
    SELECT uid AS id FROM messenger WHERE r_uid = 213
) AS temp_table
WHERE id != 213;

Both will give you the desired output:

new id
-----------
239
2. 合并同一张表中的两行数据

Merging rows depends on what exactly you need to combine—here are two common scenarios with solutions:

Scenario 1: Merge rows with shared key (e.g., same user ID) to fill missing values

If you have two rows for the same entity (like a user) with complementary data, use GROUP BY with aggregate functions to combine them:
Suppose your table user_data looks like this:

id  | name  | phone   | email
----|-------|---------|-----------
213 | Alice | 555-123 | NULL
213 | Alice | NULL    | alice@x.com

Merge into one row:

SELECT 
    id,
    MAX(name) AS name,
    MAX(phone) AS phone,
    MAX(email) AS email
FROM user_data
WHERE id = 213
GROUP BY id;

This will pick the non-null value for each column.

Scenario 2: Concatenate values from multiple rows into a single field

If you want to combine text values from multiple rows (like notes or tags), use GROUP_CONCAT:
Suppose your table user_notes looks like this:

user_id | note
--------|-------------------
213     | Meeting at 3 PM
213     | Bring project docs

Merge the notes into one field:

SELECT 
    user_id,
    GROUP_CONCAT(note SEPARATOR ' ') AS combined_notes
FROM user_notes
WHERE user_id = 213
GROUP BY user_id;

You can adjust the SEPARATOR to use commas, newlines, or whatever fits your needs.

If your merge scenario is different (like row-to-column pivoting), feel free to share more details about your table structure and desired output!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:03:45