加入涉及同一个表的2个sql查询我需要获取id

时间:2013-10-12 16:04:04

标签: mysql sql

我有这两个查询

select 
    count(1),
    female.first_name,
    female.last_name,
    male.first_name,
    male.last_name
from
    new_person as male
        left join
    new_person as female ON male.spouse_id = female.id
where
    male.spouse_id <> '0'
group by female.first_name , female.last_name , male.first_name , male.last_name;

,第二个1看起来像这样

    select 
    male.first_name as fnf,
    male.last_name as lnf,
    female.first_name as fnm,
    female.last_name as lnm
from
    new_person as p1
        left join
    new_person as male ON p1.father_id = male.id
        left join
    new_person as female ON p1.mother_id = female.id
where
    p1.last_name <> ''
        and p1.last_name <> 'N.N.'
        and ((male.last_name <> ''
        and male.last_name <> 'N.N.')
        or (female.last_name <> ''
        and female.last_name <> 'N.N.'))

现在我想将这些结合起来 其中maleq1.name = maleq2.name和femaleq1.name = femaleq2 然后在q1和q2中播下男性和女性的身份

名称我的意思是first_name和last_name

1 个答案:

答案 0 :(得分:1)

这是我的建议:从每个查询中查看。然后使用您的两个视图编写第三个查询。

但是,您的第一个查询是聚合/汇总/多个记录中的任何一个。使用id

为查询添加新字段
CREATE VIEW q1 AS
select 
    count(1),
    female.first_name,
    female.last_name,
    male.first_name,
    male.last_name,
    GROUP_CONCAT(male.id),
    GROUP_CONCAT(female.id)
from
    new_person as male
        left join
    new_person as female ON male.spouse_id = female.id
where
    male.spouse_id <> '0'
group by female.first_name , female.last_name , male.first_name , male.last_name;

然后是你的第二个查询

CREATE VIEW q2 AS
select 
    male.first_name as fnf,
    male.last_name as lnf,
    female.first_name as fnm,
    female.last_name as lnm,
    male.id AS male_id,
   female.id as female_id
from
    new_person as p1
        left join
    new_person as male ON p1.father_id = male.id
        left join
    new_person as female ON p1.mother_id = female.id
where
    p1.last_name <> ''
        and p1.last_name <> 'N.N.'
        and ((male.last_name <> ''
        and male.last_name <> 'N.N.')
        or (female.last_name <> ''
        and female.last_name <> 'N.N.'))

将这些用于第三个查询