内部联接的MySQL查询失败

时间:2012-01-19 12:43:46

标签: mysql

我正在编写一个php mysql应用程序,我正在运行以下选择查询:

SELECT 
    individual_marriage.pk_marriage_ID, 
    husband.individual_person_FirstName, 
    husband.individual_person_LastName, 
    wife.individual_person_FirstName, 
    wife.individual_person_LastName 
FROM 
    (
        (
            individual_marriage AS im 
            INNER JOIN person AS husband ON 
            individual_marriage.fk_IndividualID_male=husband.pk_person
        ) 
        INNER JOIN person AS wife ON individual_marriage.fk_IndividualID_female=wife.pk_person
    ) 
WHERE 
    im.Sec5A_applicable='yes'

问题出在WHERE语句中,mysqli_query返回false。 mysql_errno()和mysql_error()也以某种方式返回空白。

3 个答案:

答案 0 :(得分:0)

SELECT  im.pk_marriage_ID, 
        husband.individual_person_FirstName, 
        husband.individual_person_LastName, 
        wife.individual_person_FirstName, 
        wife.individual_person_LastName 
FROM    individual_marriage AS im INNER JOIN person AS husband
                ON im.fk_IndividualID_male = husband.pk_person
        INNER JOIN person AS wife
                ON im.fk_IndividualID_female = wife.pk_person) 
WHERE   im.Sec5A_applicable = 'yes'

如果您可以发布表格的SCHEMA,我们可以提供更多帮助。如果您运行此查询并返回空行,表示individual_marriage中的列不在表person 中,并且因为您还在使用 INNER JOIN

<强>更新

SELECT  im.pk_marriage_ID, 
        COALESCE(husband.individual_person_FirstName,'') as  husbandFirstName
        COALESCE(husband.individual_person_LastName, '') as  husbandFamilyName
        COALESCE(wife.individual_person_FirstName,'') as    WifeFirstName
        COALESCE(wife.individual_person_LastName ,'') as    WifeLastName
FROM    individual_marriage AS im LEFT JOIN person AS husband
                ON im.fk_IndividualID_male = husband.pk_person
        LEFT JOIN person AS wife
                ON im.fk_IndividualID_female = wife.pk_person) 
WHERE   im.Sec5A_applicable = 'yes'

答案 1 :(得分:0)

如果您可以通过执行以下查询来附加表indivisual_marriage和person表的CREATE表结构: SHOW CREATE TABLE indivisual_marriage; SHOW CREATE TABLE person;

同样告诉你要用两个表实现什么,我们可以构建一个比这个更好的查询

答案 2 :(得分:0)

我从愚蠢的运气中解决了这个问题。我所要做的就是在FROM子句中第一个表的名称周围添加一组新的括号。我在这里复制代码:

SELECT 
individual_marriage.pk_marriage_ID,  
husband.individual_person_FirstName, 
husband.individual_person_LastName, 
wife.individual_person_FirstName, 
wife.individual_person_LastName
FROM 
   (((individual_marriage) 
INNER JOIN
person AS husband
ON 
individual_marriage.fk_IndividualID_male=husband.pk_person) 
INNER JOIN
person AS wife
ON 
individual_marriage.fk_IndividualID_female=wife.pk_person) 
WHERE 
individual_marriage.Sec5A_applicable='yes'

这对我来说没有意义。到目前为止,我还没有在任何教科书中看到过这样的解决方案。有人可以解释在添加这些括号后语句的含义是如何变化的吗?