PHP SQL连接表行作为键

时间:2012-09-26 10:30:33

标签: php sql join

我想知道是否有人可以帮助我。我有以下两个表:

---Posts----

id  | title | content |  
544 | Alan  | Blah

---Postmeta----

metaid | post_id | meta_key | meta_value  
1      |  544    | age      | 45  
2      |  544    | email    | test@hotmail.co.uk

我想通过post_id加入这两个表,然后显示meta_keys。像这样的东西

SELECT posts.post_id, 
       postmeta.age, 
       postmeta.email, 
FROM 
       posts  
JOIN posts 
ON posts.post_id = postmeta.post_id 

非常感谢任何帮助。干杯

6 个答案:

答案 0 :(得分:3)

您需要PIVOT将表postmeta内的行CASE放入列中,使用MAX NULL作为聚合函数来消除SELECT p.id, pm.age, pm.email FROM posts p JOIN ( SELECT post_id, MAX(CASE WHEN meta_key = 'age' THEN meta_value END) AS age, MAX(CASE WHEN meta_key = 'email' THEN meta_value END) AS email FROM postsmeta GROUP BY post_id ) pm ON p.id = pm.post_id

age

这是Demo in sql fiddle

请注意:您当前正在将emailvarchar的所有值存储在同一数据类型的一列中,例如age您必须在查询中将INT值转换为INT,以便在以后执行某些计算时将其设置为{{1}},并且我已将此部分留给您。 / p>

答案 1 :(得分:1)

SELECT
  posts.id,
  postmeta.key,
  postmeta.meta_value
FROM
  posts
JOIN
  postmeta ON posts.id = postmeta.post_id
WHERE
  postmeta.key IN ('age', 'email')

答案 2 :(得分:0)

应该是这样的

SELECT posts.post_id,
postmeta.age,
postmeta.email,
FROM
posts
JOIN postsmeta
ON posts.post_id = postmeta.post_id

答案 3 :(得分:0)

SELECT posts.id, 
       postmeta.age, 
       postmeta.email, 
       m.meta_key, 
       m.meta_value
FROM 
       posts  p
JOIN Postmeta m
ON p.id = m.post_id 

答案 4 :(得分:0)

加入两次postmeta表:

SELECT p.id, 
       pm1.meta_value AS age, 
       pm2.meta_value AS email
FROM 
       posts AS p
  LEFT JOIN 
       postmeta AS pm1
    ON pm1.post_id = p.id
   AND pm1.meta_key = 'age'

  LEFT JOIN 
       postmeta AS pm2
    ON pm2.post_id = p.id 
   AND pm2.meta_key = 'email' ;

答案 5 :(得分:0)

不要将meta_key保存在新行中,而是尝试使用这样的表结构

metaid | post_id | age | email  
1      |  544    | 45  | test1@hotmail.co.uk  
2      |  545    | 51  | test2@hotmail.co.uk  
3      |  546    | 20  | test3@hotmail.co.uk  
4      |  547    | 26  | test4@hotmail.co.uk  

您可以向表格结构中添加更多字段。

之后,您可以进行简单的连接查询,这将节省您执行查询的时间和资源。 像这样

SELECT posts.post_id, postmeta.age, postmeta.email FROM posts JOIN postmeta ON posts.post_id = postmeta.post_id;