使用复合键连接表

时间:2015-04-19 14:59:01

标签: mysql sql join

我有两个表,其中id_health_center和id_user都用作复合键:

  • health_center_review
    • id_health_center
    • id_user
    • 评论
  • health_center_grade
    • id_health_center
    • id_user
    • grade_service

我想构建一个查询,该查询将返回health_center_review中的评论,评分由同一用户给出。例如:

id_health_center | id_user | review
---------------------------------------
1                | 1       | something 1
1                | 2       | something 2

id_health_center | id_user | grade_service
-------------------------------------------
1                | 1       | 5

将返回:

id_user | review       | grade_service
----------------------------------------------------
1       | something 1  | 5
2       | something 2  | NULL

我尝试了以下查询:

SELECT hcr.id_user, review, grade_service
FROM health_center_reviews hcr
LEFT JOIN health_center_grades hcg ON hcg.id_health_center = hcr.id_health_center AND hcg.id_user = hcr.id_user
WHERE hcr.id_health_center = 1;

如果他们有分数,那只会返回评论。如果省略join子句中的用户部分,则返回其他用户的等级。

0 个答案:

没有答案