簡體   English   中英

MySQL:查詢(子查詢)中的查詢不起作用

[英]Mysql : query in a query (subquery) not working

我想在一個表上運行一個MySQL查詢,然后在這個表上運行一個子查詢。 我有一個對象列表。 每個對象都有一個主要版本和一個次要版本。 對於一個對象,我試圖找到哪個是該對象的“最后一個版本”:這意味着我想找到該對象的max(major),然后是最后一個結果的max(minor)。

我建立一個“測試” MySQL數據庫:

create database test ;  
use test ;

我創建了一個表:

create table test 
(  
    id int auto_increment,   
    object varchar(10),   
    major int,   
    minor int,  
    PRIMARY KEY (`id`)  
) engine innodb;  

我用數據填充此表:

insert into test (object, major, minor) values ('obj1',1,0) ;  
insert into test (object, major, minor) values ('obj1',1,1) ;  
insert into test (object, major, minor) values ('obj1',1,2) ;  
insert into test (object, major, minor) values ('obj1',2,0) ;  
insert into test (object, major, minor) values ('obj1',2,1) ;  

我列出了表格:從測試中選擇*;

+----+--------+-------+-------+  
| id | object | major | minor |  
+----+--------+-------+-------+  
|  1 | obj1   |     1 |     0 |  
|  2 | obj1   |     1 |     1 |  
|  3 | obj1   |     1 |     2 |  
|  4 | obj1   |     2 |     0 |  
|  5 | obj1   |     2 |     1 |  
+----+--------+-------+-------+  

設置5行(0.01秒)

第一個查詢是獲取max(major)行:

select * 
from test 
where object = 'obj1' 
  and major = (select max(major) from test);

結果如下:

+----+--------+-------+-------+  
| id | object | major | minor |  
+----+--------+-------+-------+  
|  4 | obj1   |     2 |     0 |  
|  5 | obj1   |     2 |     1 |  
+----+--------+-------+-------+  

設置2行(0.00秒)

然后我嘗試獲取次要0版本:

select * 
from 
    (select * 
     from test 
     where object = 'obj1' 
       and major = (select max(major) from test)) as t 
where 
    t.minor = 0 ;

它有效,結果是:

+----+--------+-------+-------+  
| id | object | major | minor |  
+----+--------+-------+-------+  
|  4 | obj1   |     2 |     0 |  
+----+--------+-------+-------+  

但我想要最后一個版本,所以我想找到max(minor)為1:

select * 
from 
    (select * 
     from test 
     where object = 'obj1' 
       and major = (select max(major) from test)) as t 
where 
    t.minor = (select max(minor) from t) ;

我得到錯誤:

錯誤1146(42S02):表'test.t'不存在

我不明白為什么它不起作用。

謝謝

select * from test where object = 'obj1' order by major desc, minor desc limit 1;

首先,我們對表格進行排序,以使所有具有main列的最大值的行都排在最前面( 按major desc排序 )。 如果有任何行的主列值具有相同的值,則我們通過對行進行排序以使其具有與主列相同的值,從而對它們“排序”,從而使具有次要列的最大值的行排在首位( 按次要desc排序 ) 。 因此,第一行的輸出將是具有major的最大值的行,而對於major的值,則是minor的最大值的行。 由於我們只對第一行感興趣,因此我們將輸出限制為一行( 限制為1 )。

您可以通過以下查詢實現相同

select * from test where object='obj1' and major=(select max(major) from test)
and minor = (
select max(minor) from test where object='obj1' and major=(select max(major) from test )
  )

這將產生以下結果

+----+--------+-------+-------+
| id | object | major | minor |
+----+--------+-------+-------+
| 5 | obj1 | 2 | 1 |
+----+--------+-------+-------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM