我怎样才能比较两个不同表的两个字段与mysql?

时间:2019-08-14 19:26:04

标签: mysql

类似这样的东西

select 
(
case when     
( (select t1.name from table_1 as t1)=(select t2.name from table_2 as t2) )    
then 'same'    
else 'different'     
end
);

我想将表_1中的“名称”与表_2中的“名称”进行比较,如果它们相等,它将显示在“相同名称”字段中,否则,它将显示“不相同”。

有什么我可以做的case(或其他任何东西)?

我将不得不使用多个字段(姓名,姓氏,年龄等...)来执行此操作,而我只是无法弄清楚这个简单的查询。


这是我想要的另一个比较,但现在有两列:

    Table A:
 ID - NAME - Age
 1    rick   12
 2    denis  21
 3    jane   34
 4    john   38
 5    jerry  76
 6    max    54

    Table B:
 ID - NAME - Age
 1    rick   10
 2    jay    21
 3    morris 34
 4    john   38
 5    jerry  79
 6    morty  54

将每个字段与我想要的条件进行比较的结果:

ID -   Name     -  Age
1     Same        Different
2     Different   Same
3     Different   Same
4     Same        Same
5     Same        Different
6     Different   Same

2 个答案:

答案 0 :(得分:1)

尝试这将有所帮助

 SELECT CASE 
             WHEN t2.name IS NULL THEN 'not the same' 
             ELSE 'same name' 
         END 
    FROM table_1 t1 
    LEFT JOIN table_2 t2 ON t1.name = t2.name 

答案 1 :(得分:0)

因此,在我的情况下,需要在表之间建立关系,所以就可以了:

表1

create table table1 (
    id int auto_increment,
    name varchar(40),
    age int,
    primary key (id)
    );

表2

create table table2 (
    id int auto_increment,
    name varchar(40),
    age int,
    primary key (id),
    CONSTRAINT `id` FOREIGN KEY (`id`) REFERENCES `table1` (`id`)
);

在两个表中插入一些数据...

insert into table1 (name,age) values
('morty',14),
('rick',70),
('beth',35);

insert into table2 (name,age) values
('morty',14),
('rick',50),
('beeth',35);

我想要的查询:

(select  t1.name as t1name,t2.name as t2name,
 (case
  when t1.name = t2.name then 'same' else 'dif'
 end) as resultName, t1.age as age1,t2.age as age2,
 (case
  when t1.age = t2.age then 'same' else 'dif'
 end) as resultAge
 from table1 as t1
 left join table2 as t2 on t1.id = t2.id
 )
  order by t1name,t2name;

结果:

t1name  t2name  resultName    age1  age2  resultage
beth    beeth   dif           35    35    same
morty   morty   same          14    14    same
rick    rick    same          70    50    dif
相关问题