简体   繁体   English

MySQL查询以选择表2中与表1匹配的所有结果

[英]MySQL query to select all results from table 2 that match table 1

I have pages stored in the database, and another table that stores translations of that same page: 我有存储在数据库中的页面,还有另一个存储该页面翻译的表:

Table page_pages: 表格page_pages:

ID    Title        Content
1     First Page   Stuff...
2     Second Page  More stuff...

Table page_translations: 表page_translations:

ID    PageID    LanguageID    Title             Content
1     1         2             Primero pagina    Cosas...

So, right now I am querying the page_pages table to get the page information: 因此,现在我正在查询page_pages表以获取页面信息:

$query = SELECT * FROM page_pages WHERE ID = 1

How do I adjust this query to select translations that exist with the PageID AS Translations , and have that be it's own array with the LanguageID as the array keys? 如何调整此查询以选择与PageID AS Translations一起存在的Translations ,并将其作为LanguageID作为数组键的它自己的数组?

This way, I can check if a translation exists like: 这样,我可以检查翻译是否存在,例如:

$language_id = 1;

if (isset($query['Translations'][$language_id])) {
  echo $query['Translations'][$language_id]['Title'];

} else {
  echo $query['Title'];
}

You need to use MySQL's group_concat function with 'left join', eg: 您需要将MySQL的group_concat函数与“ left join”一起使用,例如:

SELECT
    pp.id,
    pp.title,
    pp.content,
    group_concat(pl.language_id) AS languages
FROM
    page_pages pp
LEFT JOIN page_translations pl ON pp.id = pl.pageID
WHERE
    pp.id = 1
GROUP BY
    pp.id;

Here's the SQL Fiddle . 这是SQL Fiddle

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

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