如何从另一个表中加入少量行的1个表?

时间:2018-01-09 16:49:56

标签: php mysql join

我有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
--------------------------------------------------

任何想法?

2 个答案:

答案 0 :(得分:0)

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

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'

答案 1 :(得分:0)

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'