MySQL:将具有多个结果行的表连接到一行

时间:2015-02-22 15:09:42

标签: mysql join

我有4张桌子:

secu_content
| id  | created    | modified   |
| 910 | 26/12/1982 | 28/12/1984 |
| 911 | 24/12/1982 | 25/12/1984 |

secu_data
| element_id | field_id | data       |
|          1 |        1 | 25/12/1984 |
|          2 |        1 | 26/12/1984 |
|          3 |        1 | 27/12/1984 |
|          4 |        1 | 25/12/1984 |
|          4 |        2 | google.com |

secu_elements
| id | item_id |
|  1 |     891 |
|  2 |     711 |
|  3 |     204 |
|  4 |     911 |

secu_fields
| id | type  |
|  1 | date  |
|  2 | input |

表secu_content,包含许多文章,其中id是文章ID。 其他3个表提供了额外的信息,我想加入它们。

我想获得包含所有secu_content行和所有列的结果+ calc_date + calc_link

calc_date< - 来自secu_data的数据列,其中field_id = 1(参见secu_fields)

calc_link< - 来自secu_data的数据列,其中field_id = 2(参见secu_fields)

问题是我得到2行secu_content id = 911(一行有正确的calc_date,第二行有正确的calc_link),我需要两行。

这是我的SQL:

SELECT a.id
     , a.created
     , a.modified
     , fe.item_id AS calc_date_item_id
     , fd.data AS calc_date
     , CASE WHEN fd.data IS NOT NULL AND ff.type = "date" THEN fd.data 
            WHEN a.modified = '0000-00-00 00:00:00' THEN a.created ELSE a.modified 
       END as calc_date
     , CASE WHEN fd.data IS NOT NULL AND ff.type = "input" THEN fd.data 
       END as calc_link 
  FROM secu_content AS a 
  LEFT 
  JOIN secu_fieldsandfilters_elements AS fe 
    ON fe.item_id = a.id 
   AND fe.content_type_id=1 
  LEFT 
  JOIN secu_fieldsandfilters_data AS fd 
    ON fd.element_id = fe.id 
  LEFT 
  JOIN secu_fieldsandfilters_fields as ff 
    ON ff.id = fd.field_id 
 ORDER BY a.id DESC;

提前致谢

以色列

1 个答案:

答案 0 :(得分:0)

快速而肮脏的解决方案是使用第二次连接到secu_data(简化,添加你需要的逻辑)

SELECT id, d1.data as `calc_date`, d2.data as `calc_link`
FROM secu_content 
LEFT JOIN secu_data d1 ON secu_content.id = d1.element_id AND field_id = 1
LEFT JOIN secu_data d2 ON secu_content.id = d2.element_id AND field_id = 2