mysql 用于查找两个特定行之和的SQL查询

mzaanser  于 2023-02-28  发布在  Mysql
关注(0)|答案(3)|浏览(152)

这是我的table

id      name         age          role
---------------------------------------
1       Rahul            20              1
2       Karan            35              0
3       Vivek            47              0
4       Shubham          40              1
5       Paras            87              1
6       Arjun            18              1
7       Ayush            28              0

我只想选择年龄之和等于60的两行,就像上表中的第1行和第4行一样。SQL查询是什么?
我试过这个

select * from form_data where age=(select age from form_data having sum(age)=60);
ct3nt3jp

ct3nt3jp1#

这是CROSS JOIN的一个用例,它使用form_data表两次,从2个表中获取所有行的组合:

SELECT *
FROM form_data a
    CROSS JOIN form_data b
WHERE a.age + b.age = 60
    -- the following condition prevents getting a combination twice
    AND a.id < b.id
mfpqipee

mfpqipee2#

一种方法是将同一个表视为第二个表并将它们连接起来

select fd1.name as name1, fd2.name as name2, fd1.age as age1, fd2.age as age2
from form_data as fd1, form_data as fd2 
where fd1.age+fd2.age = 60

这会给予出两个匹配的名字和两个匹配的年龄。但是,这也会给出拉胡尔+舒巴姆和舒巴姆+拉胡尔。
避免这种情况的一种方法是使用id

select fd1.name as name1, fd2.name as name2, fd1.age as age1, fd2.age as age2
from form_data as fd1, form_data as fd2 
where fd1.age+fd2.age = 60 and fd2.id > fd1.id
5vf7fwbs

5vf7fwbs3#

使用该表:

CREATE TABLE IF NOT EXISTS users(
`id` int,
`name` VARCHAR(10),
`age` INT,
`role` INT
);

INSERT INTO `testing_database`.`users` (`id`,`name`,`age`,`role`)
VALUES
(1,       "Rahul",          20,              1),
(2,       "Karan",          35,              0),
(3,       "Vivek",          47,              0),
(4,       "Subam",          40,              1),
(5,       "Paras",          87,              1),
(6,       "Arjun",          18,              1),
(7,       "Ayush",          28,              0)

我已经用这个查询返回了数据:

SELECT t1.id, 
       t1.name, 
       t1.role, 
       t1.age as t1_age, 
       t2.age as t2_age,
       (t1.age  + t2.age ) as sum_age
FROM testing_database.users as t1
CROSS JOIN testing_database.users as t2
ON t1.id != t2.id
WHERE (t1.age  + t2.age) = 60

相关问题