简体   繁体   English

MySQL查询帮助获取结合两个表的数据

[英]MySQL query help to fetch data combining two tables

I have following tables 我有下表

articles_category article_category

id    title    sef_title

articles_data article_data

id    cat_id    title    sef_title    details

On each table "id" is the primary key and articles_data.cat_id is foreign key of articles_category 在每个表上,“ id”是主键,articles_data.cat_id是articles_category的外键

I need to fetch one latest article data for each articles category with following data. 我需要获取每个文章类别的最新文章数据以及以下数据。

articles_category.id
articles_category.title
articles_category.sef_title
articles_data.id
articles_data.cat_id
articles_data.title
articles_data.sef_title
articles_data.details

I tried with following query but it displays first article (oldest entry) rather than latest one. 我尝试了以下查询,但显示的是第一篇文章(最早的条目),而不是最新的文章。

SELECT
    articles_category.id as article_cat_id, articles_category.sef_title as cat_sef_title, articles_category.title as cat_title,
    articles_data.id, articles_data.cat_id as listing_cat_id, articles_data.title, articles_data.sef_title, articles_data.details
FROM articles_category, articles_data
WHERE articles_category.id = articles_data.cat_id
GROUP BY articles_data.cat_id
ORDER BY articles_data.id DESC

if it's a one to many relation, try (untested): 如果是一对多关系,请尝试(未经测试):

SELECT * 
FROM articles_category, articles_data 
WHERE articles_category.id = articles_data.cat_id 
  AND articles_data.id in (
     SELECT max(articles_data.id) 
     FROM articles_data GROUP BY cat_id
  )

you are not guaranteed a particular row on a GROUP BY 您不能保证GROUP BY上的特定行

and you should really use a date on your article as the max id is never guaranteed to be the latest article even if you are using autoincrement 并且您确实应该在文章上使用日期,因为即使使用自动递增功能,也不能保证最大id始终是最新文章

ORDER affects the display of records after the GROUP function has been performed. 执行GROUP功能后,ORDER将影响记录的显示。 The GROUP function recognizes the first record it sees in its search. GROUP函数识别在搜索中看到的第一条记录。

What you need to do is perform 2 queries. 您需要执行2个查询。 The first one should be 第一个应该是

SELECT max(articles_data.id), articles_data.cat_id ... 
GROUP BY articles_data.cat_id

The second query should fetch the associated records using those resultant primary keys. 第二个查询应该使用那些结果主键来获取关联的记录。

A possibility is to create another value such as date_created and place a time stamp there when creating an entry. 一种可能性是创建另一个值,例如date_created,并在创建条目时在此处放置时间戳。

Then you would just have to ORDER BY date. 然后,您只需ORDER BY日期即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM