来自3个表的mysql SELECT,其中2个表可以为null

时间:2013-11-29 02:20:49

标签: php mysql sql select

我想请你帮忙查询一下(mysql)。我有3张桌子:

1.table“评论”

ID     | content                     |
--------------------------------------
1      | content of first review
2      | content of second review

2.table“pros”

ID     |  reviews_ID  |  pros         |
---------------------------------------
1      |          1   |  good service |
2      |          1   |  nice look    |
3      |          1   |  not bad price|
4      |          2   |  good service |
5      |          2   |  design       |

3.table“cons”

ID     |  reviews_ID  |  pros         |
---------------------------------------
1      |          1   |  delays       |
4      |          2   |  mistakes     |
5      |          2   |  troubles     |

我要做的是从这3个表中合并信息,其中“reviews”表是主要的,表2,3指向它(reviews_ID)。

我想得到这样的结果:

=> content of first review
   + good service       - delays
   + nice look
   + not bad price

当然在数组/结果中,这只是为了更好地理解:)

3 个答案:

答案 0 :(得分:1)

SELECT语句仅生成二维表。因此,您无法使用STANDARD SELECT获取分层树。我建议在客户端使用SQL并转换显示格式。

SELECT 'content',r.content as value
FROM reviews r
WHERE r.ID = 1

UNION

SELECT 'pros', p.pros
FROM reviews r LEFT JOIN pros p
  ON r.ID = p.reviews_ID
WHERE r.ID = 1

UNION

SELECT 'cons', c.cons
FROM reviews r LEFT JOIN cons c
  ON r.ID = c.reviews_ID
WHERE r.ID = 1

答案 1 :(得分:1)

试试这个sqlFiddle 使用GROUP_CONCAT,您可以将利弊分解为数组或PHP中的任何内容。

SELECT content,p.pros,c.cons
FROM reviews
LEFT JOIN
  (SELECT reviews_id,GROUP_CONCAT(pros)as pros
   FROM pros
   GROUP BY reviews_id)as p
 ON p.reviews_id = reviews.id
LEFT JOIN
  (SELECT reviews_id,GROUP_CONCAT(cons)as cons
   FROM cons
   GROUP BY reviews_id)as c
 ON c.reviews_id = reviews.id
WHERE reviews.id = 1;

结果将是

CONTENT                     PROS                                    CONS
content of first review     good service,nice look,not bad service  delays

答案 2 :(得分:0)

试试这个:

SELECT A.content, B.pros, C.cons
FROM reviews A LEFT JOIN pros B ON A.ID = B.reviews_ID
  LEFT JOIN cons C ON A.ID = C.reviews_ID