如何从两个表中获取数据

时间:2019-11-12 15:26:03

标签: mysql sql postgresql

有人告诉我创建一个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的创建时间显示它们。

4 个答案:

答案 0 :(得分:1)

使用虚拟列说明不同的结构,并添加联合以将它们连接起来:

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

答案 1 :(得分:0)

您可以尝试使用UNION ALL从两个表中进行选择。

在我的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;

答案 2 :(得分:0)

除了创建数据的人以外,这两个表无关。因此,如果要显示用户创建的条目,则自然会编写两个查询:

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;

然后,您可以在应用或网站中决定如何显示数据。在两个单独的网格中?只有一个?只需遍历数据并根据您的需要进行显示即可。

答案 3 :(得分:0)

我将使用简单的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

More on MySQL unions can be found here