从3个表中检索信息

时间:2014-05-16 13:00:40

标签: mysql database join

我有三张桌子:

users:
+----------+-----------------------------+-----------+
| users_id | user detail                 | otherID   | 
+----------+-----------------------------+-----------+
|        1 | user name or details        |         1 |
|        2 | user name or details        |         1 |
|        3 | user name or details        |         4 |
|        4 | user name or details        |         1 |
|        5 | user name or details        |       21  |
|        6 | user name or details        |         2 |
+----------+-----------------------------+-----------+
photos:
+----------+----------------+-----------+--------+---------+--------------+
| photosID | url            |    title  | userID | likes   | remarksID    |
+----------+----------------+-----------+--------+---------+--------------+
|      1   |       7459.JPG |   TITLE   |      1 |     150 |       255    |
|      2   |       7510.JPG |   TITLE   |      1 |     146 |       247    |
|      3   |       7460.JPG |   TITLE   |      2 |       2 |        56    |
+----------+----------------+-----------+--------+---------+--------------+

remarks:
+-----------+---------------------------------------+---------+------------+
| remarksID | remark                                | userID  | photoID    |
+-----------+---------------------------------------+---------+------------+
|         1 | REMARKS for PhotoID 1                 |       1 |          1 |
|         2 | REMARKS for PhotoID 1                 |       1 |          1 |
|         3 | REMARKS for PhotoID 1                 |       1 |          1 |
|         4 | REMARKS for PhotoID 2                 |       1 |          2 |
|         5 | REMARKS for PhotoID 2                 |       1 |          2 |
|         6 | REMARKS for PhotoID 3                 |       2 |          3 |
+-----------+---------------------------------------+---------+------------+

我正在尝试提取给定用户照片的评论,但只想让照片出现一次,但是为每张用户照片显示照片的所有相关评论。 如果没有备注,则只显示没有备注的照片。

布局在网页上看起来像这样 -

------------------------------------
Photograph 1
         Remarks 1
         Remarks 2
         Remarks 1
------------------------------------
Photograph 2
         NO remarks for photo
------------------------------------
Photograph 3
         Remarks 1
         Remarks 2
         Remarks 3
         Remarks 4
------------------------------------
Photograph 4
         Remarks 1
         Remarks 2
------------------------------------

1 个答案:

答案 0 :(得分:0)

我的假设是正确的,你的困难是,如何让数据库这样做?如果是这样,那么答案是这个函数(格式化数据),通常不是(或不应该)数据库的责任。从一个结果集中获取数据库中的照片,然后在另一个结果集中获取匹配的注释,并让您的应用程序或报告工具按照您希望的方式格式化数据。