[英]How can I get data from two tables
我被告知要创建一个 GET /feed 端点,用户可以在其中查看所有文章或 gif,首先显示最近发布的文章或 gif。 这是我的文章和gif表
CREATE TABLE article(
article_id SERIAL PRIMARY KEY,
title VARCHAR(300),
article text ,
user_id INTEGER REFERENCES user(id) ON DELETE CASCADE,
created_on TIMESTAMP DEFAULT Now()
)
CREATE TABLE gif(
gif_id SERIAL PRIMARY KEY,
title text NOT NULL ,
cloudinary_id VARCHAR (3000),
url VARCHAR(3000) ,
user_id INTEGER REFERENCES user(id) ON DELETE CASCADE,
created_on TIMESTAMP DEFAULT Now()
)
如何根据创建的时间查询我的数据库以显示文章和 gif 表。
使用虚拟列来解释不同的结构并添加一个联合来加入它们:
SELECT * FROM (
(SELECT article_id, title, article , NULL as cloudinary_id, NULL as url, user_id, created_on, 'article' as table_name FROM article)
UNION ALL
(SELECT gif_id, title, NULL as article, cloudinary_id , url, user_id, created_on , 'gif' as table_name FROM gif)
) results
ORDER BY created_on ASC
您可以尝试从两个表中使用 UNION ALL 到 select 。
以下代码在我的 dbfiddle 中针对 MySQL 8.0 进行了语法测试。
select * from (
(select 'article' as what, article_id as id, title, NULL as cloudinary_id, NULL as url, user_id, created_on from article order by created_on desc limit 0,100
)UNION ALL(
select 'gif' as what, gif_id as id, substr(title, 1, 300), cloudinary_id, url, user_id, created_on from gif order by created_on desc limit 0,100
)
) as t order by created_on desc limit 0,100;
这两个表不相关,除了创建数据的人。 所以,如果你想显示一个用户创建的条目,你自然会写两个查询:
select * from article where user_id = $user_id order by created_on desc;
和
select * from gif where user_id = $user_id order by created_on desc;
在您的应用程序或网站中,您可以决定如何显示数据。 在两个单独的网格中? 只有一个? 只需遍历数据并根据您的需要显示。
我会使用简单的 UNION 方法从给定的表中获取简单的 Feed。 更聪明的方法是在对表进行更多迭代后使用连接。
SQL Union 的第一条规则,当您需要显示来自不同表格(如文章和 gif)的数据时,您需要将所有内容收集在一个通用名称下。
SELECT feed_id, title, article, url, user_id, created_on, feed_type FROM
(
SELECT
feed_id = article_id,
title,
article,
url='', // put an empty url column to virtual table since you need to merge it with the gif table.
user_id,
created_on,
'article' as feed_type
FROM
article
UNION
SELECT
feed_id = gif_id,
title,
article='', // put an empty article column to virtual table since you need to merge it with the gif table.
url,
user_id,
created_on
'gif' as feed_type
FROM
gif
) AS MyFeedTable
ORDER BY created_on desc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.