SQL join,sum,group-by而不是null 0

时间:2015-07-26 23:15:59

标签: mysql join group-by sum

我需要一个包含posts-id,posts-title,posts-created_at,users-name和likes-status的查询。如果不存在,likes-status应为0。我需要喜欢地位的总和。像这样:

id |title   |created_at |name  |status  |
=========================================
1  |Hello 1 |2015-07-22 |Baker |0       |    // 1 - 1
2  |Hallo 2 |2015-07-23 |Tom   |0       |    // if not exists = 0

我的尝试:

SELECT p.id, p.title, p.created_at, u.name, IFNULL(l.status, 0) as status
FROM posts p
LEFT OUTER JOIN likes l ON l.post_id = p.id
INNER JOIN users u ON u.id = p.user_id

结果:

id |title   |created_at |name  |status  |
=========================================
1  |Hello 1 |2015-07-22 |Baker |1       |    // sum this
1  |Hello 1 |2015-07-22 |Baker |-1      |    // with this
2  |Hallo 2 |2015-07-23 |Tom   |0       |

用户表

id |name  |email             |password |created_at |
====================================================
1  |Baker |baker@example.com |UHds(&   |2015-07-20 |
2  |Tom   |tom@example.com   |ihj=)?   |2015-07-21 |

帖子表

id |user_id |title   |created_at |
==================================
1  |1       |Hello 1 |2015-07-22 |
2  |2       |Hello 2 |2015-07-23 |

喜欢桌子

id |user_id |post_id |status |created_at  |
===========================================
1  |1       |1       |1      |2015-07-24  |
2  |2       |1       |-1     |2015-07-25  |

1 个答案:

答案 0 :(得分:0)

如果您使用let imageView = UIImageView(frame: cell.contentView.frame.bounds) 开始查询,那么您应该继续查询。这实际上并不会影响您的查询,这需要left join,但这仍然是一个好主意:

group by