Using id that are comma separated sql

一曲冷凌霜 提交于 2019-12-14 03:59:49

问题


If you run this query

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;

you get a list of id back like this

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

Is there a way so you can immediately use it in a other query or do you have to load it in php first?


回答1:


You can use it in another query like so:

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

Notice I added the entire query to the from statement with the alias as M. You can then JOIN M to another table or do whatever you want from there.



来源:https://stackoverflow.com/questions/19369080/using-id-that-are-comma-separated-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!