MySQL在不同的列上连接两次相同的表而没有冲突

时间:2013-09-15 14:28:29

标签: php mysql

这是查询:

SELECT * FROM property_table AS property

INNER JOIN property_classification AS classifications
        ON property.classification_id = classifications.id

INNER JOIN property_classification AS classonrequest
        ON property.classonrequest_id = classonrequest.id

WHERE property.id=5000 LIMIT 1;

请注意,我在两个字段property_classificationproperty.classification_id上使用了同一个表property.classonrequest_id

property_classification的结构类似于:

id | a1 | a2 | a3 | ... | d1 | d2

当我在MySQL Query Browser中执行上面的查询时,我得到这样的结果:

id | other 'property' fields | id | a1 | a2 | a3 | ... | id | a1 | a2 | a3 | ...

但在我的PHP脚本中,我将返回关联的数组,并且所有重复的字段名都会被覆盖。

我想要的是以表格名称返回两个连接表的查询,即:

classifications.id | classifications.a1 | classifications.a2 | classifications.a3

classonrequest.id | classonrequest.a1 | classonrequest.a2 | classonrequest.a3

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您需要使用表别名并重命名列:

SELECT classifications.id as cid,
       classifications.a1 as c_a1,
       . . .
       classificaitions.d2 as c_d2
       classonrequest.a1 as cr_a1,
       . . .
FROM property_table AS property
INNER JOIN property_classification AS classifications
        ON property.classification_id = classifications.id
INNER JOIN property_classification AS classonrequest
        ON property.classonrequest_id = classonrequest.id
WHERE property.id=5000
LIMIT 1;

为了简化您的工作,您可以运行以下查询:

select concat('c_', column_name, ', ')
from information_schema.columns
where table_name = 'classification';

这将列出第一组的所有列名称(您可以使用不同的前缀重复第二组。

答案 1 :(得分:0)

SELECT property.*, classifications.*, classonrequest.* FROM property_table AS property

INNER JOIN property_classification AS classifications
        ON property.classification_id = classifications.id

INNER JOIN property_classification AS classonrequest
        ON property.classonrequest_id = classonrequest.id

WHERE property.id=5000 LIMIT 1;

但是你仍然不会得到具体的表名。