Sql找到另一个具有相同值的表,并在输出

时间:2017-03-11 15:25:54

标签: php mysql sql pdo

我有以下两个SQL表(在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     |
 +----+---------------+--------+----------+ 

在输出中,我必须得到所有帖子的列表,并且在同一行数组中,其他帖子(id)的信息在slug中是相同的。像这样的东西

 +----+------------+--------+----------+--------------+---------------+
 | 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

首先我决定在获取foreach循环的帖子列表之后进行排序,但是当帖子列表很大时,它需要一个非常大的资源。所以我认为在SQL中它会更快但我不知道我这样做。

1 个答案:

答案 0 :(得分:0)

您似乎想要第一篇文章以及有关翻译的信息。如果你知道这些语言,那么这可能就是你想要的:

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;