gpt4 book ai didi

mysql - 合并 2 选择与限制偏移没有关系 SQL

转载 作者:行者123 更新时间:2023-11-29 15:14:50 25 4
gpt4 key购买 nike

我想将 2 个表中的 2 个选择与限制、偏移量合并起来,如下所示。

table users
id | name | createdAt
1 John 2019-04-03
2 Smith 2019-04-04
3 Bob 2019-04-05
4 Anny 2019-04-06
5 Phon 2019-04-07


table books
id | title | author_id | createdAt
1 ABC 8 2019-04-03
2 XYZ 9 2019-04-06

我尝试编写联合查询但不起作用

select users.id, users.name, null as bookTitle 
from users
union select null, null, books.title
from books
order by users.createdAt, books.createdAt
limit 4;

结果应该是

id | name | bookTitle | createdAt
1 John null 2019-04-03
null null ABC 2019-04-03
2 Smith null 2019-04-04
3 Bob null 2019-04-05

我使用sequelize.js 通过 ORM 构建查询。或者我是否必须在sequelize 处编写并使用2 个表中的FindAll 并将它们合并在一起。

最佳答案

您需要将联合的两个部分括在括号中,作为元组:

(SELECT users.id, users.name, NULL AS bookTitle FROM users)
UNION
(SELECT NULL, NULL, title FROM books ORDER BY createdAt LIMIT 4);

我还注意到您的第二个查询引用了 ORDER BY 子句中的 books 表。这没有任何意义,因为 books 不是该查询的一部分。

关于mysql - 合并 2 选择与限制偏移没有关系 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59763679/

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