【问题标题】:How do I join 1 table with few rows from another table?如何将 1 个表与另一个表中的几行连接起来?
【发布时间】:2018-01-09 16:49:55
【问题描述】:

我有 2 个表格,“pages”和“custom_fields”。

页面

--------------------------------------------------
|   id    |     title   |   
--------------------------------------------------
|    1    |     about   |
--------------------------------------------------

custom_fields

--------------------------------------------------
|   id    |     page   |  field   |   output    
--------------------------------------------------
|    1    |     1      |   color  |     red
--------------------------------------------------
|    2    |     1      |   shape  |    square

我想将“pages”中的 1 行与“custom_fields”中的所有相关行连接起来。但如果我使用简单的连接,它只会给我其中一个。我想做一个更智能的连接,使查询像这样

加入后的页面

--------------------------------------------------
|   id    |     title   |   color    |    shape
--------------------------------------------------
|    1    |     about   |    red     |    square
--------------------------------------------------

有什么想法吗?

【问题讨论】:

  • 请提供您的查询。简单的 JOIN 应该足以获得您显示的结果。

标签: php mysql join


【解决方案1】:

在这种情况下,您应该对同一个表使用两个连接,每个连接用于一个字段

select a.id, a.title, b.output as  color, c.output as shape
from pages 
inner join custom_fields b on a.id = b.page and b.field='color'
inner join custom_fields c on a.id = c.page and c.field='shape'

或者如@alex 建议的那样,如果缺少其中一种字段类型,您可以使用左连接

select a.id, a.title, b.output as  color, c.output as shape
from pages 
left join custom_fields b on a.id = b.page and b.field='color'
left join custom_fields c on a.id = c.page and c.field='shape'

【讨论】:

  • 我建议使用LEFT JOIN,所以如果我们只为页面设置colorshape -query 仍然会带来结果
  • @alex .. 正确 .. 有用 .. 根据您的建议更新答案
【解决方案2】:

http://sqlfiddle.com/#!9/9dfe66/2

SELECT p.id, p.title, 
    color.output as color,
    shape.output as shape
FROM pages p
LEFT JOIN custom_fields color 
  ON p.id = color.page AND color.field='color'
LEFT JOIN custom_fields shape 
  ON p.id = shape.page AND shape.field='shape'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多