1

这是查询:

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_classification在两个字段property.classification_idproperty.classonrequest_id.

的结构property_classification类似于:

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

当我在 MySQL 查询浏览器中执行上面的查询时,我得到如下信息:

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

我怎么做?

4

2 回答 2

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';

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

于 2013-09-15T14:35:35.093 回答
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;

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

于 2013-09-15T14:38:38.377 回答