我有一个这样的数据库表:
id version_id field1 field2
1 1 texta text1
1 2 textb text2
2 1 textc text3
2 2 textd text4
2 3 texte text5
Run Code Online (Sandbox Code Playgroud)
如果你没有解决它,它包含一行的多个版本,然后是一些文本数据.
我想查询它并返回每个id的编号最大的版本.(所以仅在上面的第二行和最后一行).
我尝试使用group by by version_id DESC进行排序 - 但它似乎在分组后进行排序,所以这不起作用.
有人有任何想法吗?我不敢相信它无法完成!
更新:
想出来,这有用,但使用子查询:
SELECT *
FROM (SELECT * FROM table ORDER BY version_id DESC) t1
GROUP BY t1.id
Run Code Online (Sandbox Code Playgroud) 我有下表:
id time text otheridentifier
-------------------------------------------
1 6 apple 4
2 7 orange 4
3 8 banana 3
4 9 pear 3
5 10 grape 2
Run Code Online (Sandbox Code Playgroud)
我想要做的是选择3个最近的记录(按时间desc),其中otheridentifiers是不同的.所以在这种情况下,结果将是id's:5,4和2.
id将跳过= 3,因为最近的记录具有相同的otheridentifier字段.
这是我试图做的事情:
SELECT * FROM `table` GROUP BY (`otheridentifier`) ORDER BY `time` DESC LIMIT 3
Run Code Online (Sandbox Code Playgroud)
然而,我最终得到的行id= 5,3,和1而不是5,4,2按预期方式.
有人能告诉我为什么这个查询不会返回我的预期吗?我尝试将ORDER BY更改为ASC,但这只是将返回的行重新排列为1,3,5.
我有以下JOIN查询:
SELECT
table1.*,
table2.*
FROM
Table1 AS table1
LEFT JOIN
Table2 AS table2
USING
(col1)
LEFT JOIN
Table3 as table3
USING
(col1)
WHERE
3963.191 *
ACOS(
(SIN(PI() * $usersLatitude / 180) * SIN(PI() * table3.latitude / 180))
+
(COS(PI() * $usersLatitude / 180) * COS(PI() * table3.latitude / 180) * COS(PI() * table3.longitude / 180 - PI() * 37.1092162 / 180))
) <= 10
AND
table1.col1 != '1'
AND
table1.col2 LIKE 'A'
AND
(table1.col3 LIKE 'X' OR table1.col3 LIKE 'X-Y') …Run Code Online (Sandbox Code Playgroud) 我在mysql(innodb)上有一张大桌子,其中包含产品资产(1300万行)。这是我的数据库的一些架构:
product <-many2one-- file_item --one2many--> family --many2one--> download_type
Run Code Online (Sandbox Code Playgroud)
* file_item *表是具有数百万行的大表。我尝试使用以下sql查询按下载类型对产品进行计数:
select t.name as type,
count(p.product_id) as n
from file_item p
inner join family f on f.id = p.family_id
inner join type t on f.id_type = t.id
group by t.id order by t.name;
Run Code Online (Sandbox Code Playgroud)
* file_item *表上有3个索引:
+ ---- + ------------- + ------- + -------- + ------------- ---------------------- + --------- + --------- + ------- ------------ + ---------- + -------------------------- ------- + | id | select_type | 桌子| 类型 …