在没有笛卡尔积的单个mysql查询中有多个多对多JOIN

时间:2010-06-15 05:54:45

标签: mysql join many-to-many cartesian-product

目前,我可以通过两个单独的SELECT语句获得我需要的结果

SELECT 
COUNT(rl.refBiblioID) 
FROM biblioList bl 
LEFT JOIN refList rl ON bl.biblioID =  rl.biblioID 
GROUP BY bl.biblioID

SELECT
GROUP_CONCAT(
CONCAT_WS( ':', al.lastName, al.firstName )
ORDER BY al.authorID ) 
FROM biblioList bl 
LEFT JOIN biblio_author ba ON ba.biblioID = bl.biblioID
JOIN authorList al ON al.authorID = ba.authorID 
GROUP BY bl.biblioID

然而将它们组合起来

SELECT
GROUP_CONCAT(
CONCAT_WS( ':', al.lastName, al.firstName )
ORDER BY al.authorID ),
COUNT(rl.refBiblioID) 
FROM biblioList bl 
LEFT JOIN biblio_author ba ON ba.biblioID = bl.biblioID
JOIN authorList al ON al.authorID = ba.authorID 
LEFT JOIN refList rl ON bl.biblioID =  rl.biblioID
GROUP BY bl.biblioID

导致作者结果列具有重复的名称。如何在不使用DISTINCT的情况下从一个SELECT语句中获得所需的结果?使用子查询?

1 个答案:

答案 0 :(得分:1)

如果子选择是可以接受的,我相信你可以通过做这样的事情来实现这个目标:

SELECT
  y.authors,
  COUNT(rl.refBiblioID) 
FROM
  (SELECT
    bl.biblioId,
    GROUP_CONCAT(
      CONCAT_WS(':', al.lastName, al.firstName)
      ORDER BY al.authorID) AS authors
  FROM biblioList bl
  LEFT JOIN biblio_author ba ON ba.biblioID = bl.biblioID
  JOIN authorList al ON al.authorID = ba.authorID 
  GROUP BY bl.biblioID) y
LEFT JOIN refList rl ON (y.biblioID =  rl.biblioID)
GROUP BY y.biblioID

另一个解决方案是将DISTINCT添加到GROUP_CONCAT,但这不是您想要的?

GROUP_CONCAT(
  DISTINCT(CONCAT_WS(':', al.lastName, al.firstName) ORDER BY al.authorID)),