使用逗号分隔的sql的id

时间:2013-10-14 20:51:03

标签: mysql sql join subquery

如果您运行此查询

select 
    GROUP_CONCAT(p1.id) _fid,
    GROUP_CONCAT(p2.id) _mid,
    count(1)
from
    new_person as pb
        inner join
    new_person as p1 ON pb.father_id = p1.id
        inner join
    new_person as p2 ON pb.mother_id = p2.id
where
    (p1.last_name <> 'N.N.'
        and p1.last_name <> '')
        or (p2.last_name <> 'N.N.'
        and p2.last_name <> '')
group by p1.first_name , p1.last_name , p2.first_name , p2.last_name
having count(1) > 1;

你会得到一个像这样的身份列表

'4676,6088,4804,4968,6554,5212,5504,5810,7298,7782,6970'

有没有办法让你可以在其他查​​询中立即使用它,或者你必须先在php中加载它吗?

1 个答案:

答案 0 :(得分:1)

您可以在其他查​​询中使用它,如下所示:

SELECT M.*, P.* FROM 
(  

  SELECT GROUP_CONCAT(p1.id) _fid, GROUP_CONCAT(p2.id) _mid, count(1)
  FROM new_person AS pb
     INNER JOIN new_person AS p1 ON pb.father_id = p1.id
     INNER JOIN new_person AS p2 ON pb.mother_id = p2.id
  WHERE (
     p1.last_name <> 'N.N.'
     AND p1.last_name <> '')
     OR (p2.last_name <> 'N.N.'
     AND p2.last_name <> '')
  GROUP BY p1.first_name, p1.last_name, p2.first_name, p2.last_name
  HAVING COUNT(1) > 1

) AS M INNER JOIN new_person as p ON M._fid = p.id

注意我将整个查询添加到from语句中,别名为M。然后,您可以JOIN M到另一张桌子或从那里做任何你想做的事。