MySQL:查询形成两个单独的ID列表并制作一个统一列表,没有重复值

时间:2015-06-19 08:59:58

标签: mysql sql

我有一个如下表格,我正在尝试合并阻止用户和逐列,并删除交叉值并创建一个唯一数字列表,但字面上我无法获得特定用户阻止列表。

|------------------------------------------------------
|block_id  | block_user |  block_by  |  block_at
|------------------------------------------------------
| 1        | 22         | 1          | 1434451573
| 7        | 59         | 1          | 1434695298
| 10       | 4          | 1          | 1434695327
| 11       | 1          | 14         | 1434695349

我需要以下内容,需要通过id的查询;

|-----------
|block_list 
|-----------
| 4
| 14
| 22
| 59

我正在尝试SQL如下,从字面上看,我未能得到理想的结果;

SELECT block_user AS blocked_user FROM block_list
UNION 
 SELECT block_by AS blocked_list FROM block_list
WHERE (block_user =  '1' OR block_by =  '1')

2 个答案:

答案 0 :(得分:1)

如果总是排除1,您可以直接使用:

SELECT *
FROM (
    SELECT block_user as id
    FROM yourTable
    UNION
    SELECT block_by as id
    FROM yourTable
) as dat
WHERE dat.id <> 1

如果您的逻辑需要,可能需要将WHERE block_user = 1添加到子查询中。这不是很清楚。

答案 1 :(得分:0)

尝试类似:

SELECT block_user
FROM (
     SELECT block_user AS blocked_user FROM block_list
     UNION 
     SELECT block_by AS blocked_user FROM block_list
     WHERE (block_user =  '1' OR block_by =  '1'))
WHERE block_user != '1'