我是SQL新手,需要帮助组合三个SQL查询。
查询1
SELECT max(level) level FROM tablename WHERE id = 1
在此示例中,结果为3,此值将用于查询2。
查询2
SELECT max(run) run FROM tablename WHERE id = 1 AND level = 3;
在此示例中,结果为1,此值将用于查询3。
查询3
SELECT levelpassed FROM tablename WHERE id = 1 AND level = 3 AND run = 1;
这是表格的结构:
CREATE TABLE `tablename` (
`id` int(11) NOT NULL,
`date` datetime NOT NULL,
`level` int(11) NOT NULL,
`run` int(11) NOT NULL,
`cr` int(11) NOT NULL,
`fr` int(11) NOT NULL,
`dv` int(11) NOT NULL,
`levelpassed` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
以下是主键:
ALTER TABLE `tablename`
ADD PRIMARY KEY (`id`,`date`);
我需要知道查询中的所有三个值。最高等级,最高行程和等级。
感谢您的帮助!
答案 0 :(得分:0)
这是您正在寻找的查询:
SELECT *
FROM tablename T
INNER JOIN (SELECT T2.id
,MAX(T2.level) AS [level]
FROM tablename T2) TL ON TL.id = T.id
AND TL.level = T.level
INNER JOIN (SELECT T3.id
,MAX(T3.run) AS [run]
FROM tablename T3) TL ON TR.id = T.id
AND TR.run = T.run
WHERE T.id = 1
希望这可以帮助您解决问题。
答案 1 :(得分:0)
您是否有查询结果输出?
请尝试:
select levelpassed from tablename a where id = 1 and run = (select max(run) from tablename b where a.id = b.id) and level = (select max(level) from tablename c where a.id = c.id);
答案 2 :(得分:-1)
尝试查询如下:
SELECT levelpassed ,
(SELECT max(LEVEL) LEVEL
FROM tablename
WHERE id = 1) level,
(SELECT max(run) run
FROM tablename
WHERE id = 1
AND LEVEL = 3) run
FROM tablename
WHERE id = 1
AND LEVEL =
(SELECT max(LEVEL) LEVEL
FROM tablename
WHERE id = 1)
AND run =
(SELECT max(run) run
FROM tablename
WHERE id = 1
AND LEVEL = 3);
实际上这是非常低效的,但它应该做你需要的。