为什么这两个表成为一个表联合,在MySQL中显示无效结果?

时间:2012-01-23 11:37:02

标签: mysql sql union

我有一个table1(记录3)和table2(记录3)。

  • 我在两者中都有字段名称。
  • 现在我想从这两个表中得到一个结果
  • 将显示两个表记录,如果有重复,则只显示一个。
  • 从该结果我将使用like或其他逻辑语句进行主查询
  • 所以我的预期输出记录将包含5行而不是6行。我该怎么做?

示例:

table1:                       table2:

+-------------------------+   +--------------------------------+
| Name            | ID        | Name            | ID
+--------------------------   +---------------------------------
| A               |  1        | 1 December Name | 4
| B               |  2        | D               | 5
| 1 December Name |  3        | E               | 6


My Expected output is following which works, but does not work when i use WHERE
like to only get '1 December Name':

+-----------------------------------------------------+
| Name               | ID                
+-----------------------------------------------------
| A                  | 1 table1
| B                  | 2 table1
| 1 December Name    | 3 table2 or table1 (no unique)
| D                  | 4 table2
| E                  | 5 table2

我试过了:

SELECT * FROM 
(
    ( 
     SELECT name AS name FROM table1 
    ) 
UNION 
    ( 
     SELECT anothername AS name FROM table2 
    )
) as t
WHERE name like '%1 December Name%'
    limit 1,10

输出:您的SQL查询已成功执行(查询耗时0.2798秒)

问题:以下查询没有错误,但找不到包含“12 December Name”

的记录

跟进:工作我现在知道它使用了哪个ID

SELECT NAME, ID, STATUS FROM 
(
 (
   SELECT NAME AS name       , id, CONCAT('table1')   AS STATUS FROM table1
 )
UNION ALL
 (
   SELECT ANOTHERNAME AS name, id, CONCAT( 'table2' ) AS STATUS FROM table2
 )
) AS t

WHERE 

 t.NAME LIKE '%1 December Name%'

LIMIT 1 , 10;

2 个答案:

答案 0 :(得分:2)

你可以得到类似你想要的东西:

select name, group_concat(id) from
(select name, 'table1' as id from table1
union all 
select name, 'table2' from table2) x
group by name

输出将是:

+------------------------------------+
| Name               | ID                
--------------------------------------
| A                  | table1
| B                  | table1
| 1 December Name    | table1,table2
| D                  | table2
| E                  | table2

UNION ALL是正确的选择(不是UNION),因为它删除重复项,并保留行顺序

答案 1 :(得分:0)

试试这个 (SELECT name FROM table1) UNION(SELECT name FROM table2);