当MySQL

时间:2016-08-31 14:22:06

标签: mysql

我有两个表,两个表都有相同的列,但是一个表有额外的列。我需要根据一个列从两个列中选择唯一记录,即下表中的profilelink存在于两个表中。

我尝试以下方式结合:

SELECT * FROM t1
UNION
SELECT * FROM t2

但我认为检查表中的所有列然后取出结果但在我的情况下,两个表中的列计数不相同,我只需要在一列的基础上获取记录。所以有人可以帮我解决这个问题。

表结构如下

表1

id  |   name    |   marks   |   profilelink
1   |   a       |   10      |   http://example.com/a
2   |   b       |   20      |   http://example.com/b
3   |   c       |   30      |   http://example.com/c
4   |   d       |   40      |   http://example.com/d

表2

id  |   name    |   marks   |   Division    |   Result  |   profilelink
1   |   e       |   10      |   I           |   Pass    |   http://example.com/e
2   |   f       |   20      |   II          |   Pass    |   http://example.com/f
3   |   b       |   30      |   III         |   Pass    |   http://example.com/b
4   |   c       |   40      |   IV          |   Fail    |   http://example.com/c    

预期结果将是

id  |   name    |   marks   |   Division    |   Result  |   profilelink
1   |   a       |   10      |   null        |   null    |   http://example.com/a
2   |   d       |   40      |   null        |   null    |   http://example.com/a
3   |   e       |   10      |   I           |   Pass    |   http://example.com/e
4   |   f       |   20      |   II          |   Fail    |   http://example.com/f

在上面的示例中,profilelink在两个表中都很常见。结果顺序无关紧要。

4 个答案:

答案 0 :(得分:0)

确定。您可以选择每个表的特定列名称,但顺序相同,如下所示:

SELECT t1_id AS id
     , t1_name AS name 
  FROM t1 
 UNION 
SELECT t2_id 
     , t2_name 
  FROM t2

答案 1 :(得分:0)

正如您所说的那样,您希望从两个表中获取不重复的记录。以下查询可能会帮助您。

SELECT id, name, marks, profilelink, count(id) as count FROM 
    (SELECT id, name, marks, profilelink 
            from table1 
    UNION 
        SELECT id, name, marks, profilelink from table2) A 
GROUP BY profilelink where count = 1

子查询将从两个表中获取记录并根据profileurl计算记录。

答案 2 :(得分:0)

i had try and get all column as result with this Query :

 SELECT  `id`, `name`, `marks`, `Division`, `Result`, `profilelink`
      FROM table_b 
     UNION 
 SELECT  `id`, `name`, `marks`,'' as 'Division','' as 'Result', `profilelink`
      FROM table_a

Output & Example :
enter image description here

答案 3 :(得分:0)

请尝试此查询:

SELECT `id`, `name`, `marks`, `Division`, `Result`, `profilelink` from (
SELECT `id`, `name`, `marks`, `Division`, `Result`, `profilelink`,  count(id) as count from (
SELECT  `id`, `name`, `marks`, `Division`, `Result`, `profilelink`
  FROM table_b 
 UNION 
SELECT  `id`, `name`, `marks`,null as 'Division',null as 'Result', `profilelink`
  FROM table_a )tbl  group by name )  tbl_Val where  count=1  ;