gpt4 book ai didi

mysql - 查询在 mySql 中工作而不在 Oracle 中工作

转载 作者:行者123 更新时间:2023-11-29 02:41:02 24 4
gpt4 key购买 nike

下面是在 MySQL 中有效但在 Oracle 中无效的查询。在这里我需要从表 r 中获取最新的日期和相应的事件 对于表 a 中的每个 ID。 ID 是唯一的。


 SELECT a.name , a.spids , a.group , a.id , r.date,r.event  FROM a
LEFT OUTER JOIN ( SELECT id, MAX(date) AS latest FROM r GROUP BY id ) AS rev
ON rev.id = a.id
LEFT OUTER JOIN r ON r.id = rev.id
AND r.date = rev.latest
group by a.id order by ID;
---------------------------------------------
*The error in Oracle is "Not a group by function"
I read several blogs about group by function and every where they are saying to use an aggregate funciton like sum , min,max. I tried but not able to get the results*
-----------------------
Table a ( It has other column - group also)
-----------------------


ID Name Spids
1 SIML TRDR,THYU
2 SIML YUIL
3 ghhe yhgu,hjuy,kiuj
4 th yuio


-----------------------
Table r ( Needs to get the latest updated date and corresponding event details for every ID)
-----------------------


ID Event Date
1 by chris 02-02-2016
1 by Steve 02-02-2013
1 by gen 02-02-2014
2 by Pete 12-12-2018
2 by ken 01-02-2014
3 by Mike 20-08-2018
3 by chin 20-08-2017
4 by chn 04-06-2012
4 by tink 06-06-2017

Output should be like this ---------------------------

NAMe     SPIDS           GROUP      ID      DATE                  EVENT
SIML TRDR,THYU Test 1 02-02-2016 by chris
SIML YUIL Test 2 12-12-2018 by Pete
ghhe yhgu,hjuy,kiuj Test2 3 20-08-2018 by Mike
th yuio Test1 4 06-06-2017 by tink

最佳答案

您的选择是:

select a.name , a.spids , a.group , a.id , r.date, r.event

您的分组依据是:

 group by a.id

这些是不兼容的——除了 a.id 之外,select 中所有其他列的值是什么。 MySQL 支持这是数据库的一个(错误的)特性,几乎任何其他数据库都不支持。

最典型的解决方案是修复这些,使它们兼容:

select a.name, a.spids, a.group, a.id, max(r.date), max(r.event)

您的分组依据是:

 group by a.name , a.spids , a.group , a.id

在您的情况下,可能根本不需要 group by:

SELECT a.name, a.spids, a.group, a.id, r.date, r.event  
FROM a LEFT OUTER JOIN
(SELECT id, MAX(date) AS latest
FROM r
GROUP BY id
) rev
ON rev.id = a.id LEFT JOIN
r
ON r.id = rev.id AND r.date = rev.latest
ORDER BY ID;

只有当有多行具有相同的最大日期时才需要它。

Oracle 中最常见的解决方案解决了这个问题:

SELECT a.name, a.spids, a.group, a.id, r.date, r.event  
FROM a LEFT JOIN
(SELECT r.*,
ROW_NUMBER() OVER (PARTITION BY r.id ORDER BY r.date DESC) as seqnum
FROM r
) rev
ON rev.id = a.id AND seqnum = 1
ORDER BY ID;

关于mysql - 查询在 mySql 中工作而不在 Oracle 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52002567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com