dqftyn1717 2017-03-11 15:25
浏览 34
已采纳

Sql找到具有相同值的另一个表,并在输出中添加它们的ID

I've got the following two SQL tables (in MySQL):

 Posts Tables
 +----+---------------+--------+----------+ 
 | id | title         |  slug  | language |
 +----+---------------+--------+----------+ 
 | 1  | Post title    | slug_1 |  eng     |
 | 2  | Another title | slug_2 |  eng     |
 | 3  | Title German  | slug_1 |  ger     |
 | 4  | Again German  | slug_3 |  ger     |
 | 5  | Russian title | slug_1 |  rus     |
 +----+---------------+--------+----------+ 

In output i am have to get list of all Posts and in the same line of array the information of other posts (id) where slug is same. Something like this

 +----+------------+--------+----------+--------------+---------------+
 | id | title      |  slug  | language | german trans | russian trans |
 +----+------------+--------+----------+--------------+---------------+
 | 1  | Post title | slug_1 |  eng     | 3            | 5
 | 2  | Another ti | slug_2 |  eng     | null         | null
 | 4  | German tit | slug_3 |  null    | 4            | null

First i decided do this-sorting after getting list of posts with foreach loop but it takes a really big resource when list of posts is big. so i think in sql it will be much faster but i dont know i to do this.

  • 写回答

1条回答 默认 最新

  • doumen5491 2017-03-11 15:34
    关注

    You seem to want the first post, along with information about translations. If you know the languages then this probably does what you want:

    select s.minid,
           max(case when p.id = s.minid then title end) as title,
           s.slug,
           max(case when p.id = s.minid then language end) as language,
           max(case when p.lang = 'ger' then id end) as German,
           max(case when p.lang = 'rus' then id end) as Russian
    from posts p join
         (select slug, min(id) as minid
          from posts p
          group by slug
         ) s
         on p.slug = s.slug
    group by p.slug;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)