在MySQL子查询中选择多个列/字段

时间:2011-04-16 11:52:55

标签: mysql

基本上有属性表和转换表 - 一个属性的许多翻译。

我需要为指定语言中的每个属性选择翻译的id和值,即使该语言中没有翻译记录。我错过了一些连接技术或连接(不涉及语言表)在这里不起作用,因为以下不返回具有指定语言的非现有翻译的属性。

select a.attribute, at.id, at.translation 
from attribute a left join attributeTranslation at on a.id=at.attribute
where al.language=1;

所以我使用这样的子查询,这里的问题是使用相同的参数对同一个表进行两个子查询(感觉就像性能耗尽,除非mysql对那些进行分组,我怀疑它会让你做很多类似的子查询)

select attribute, 
(select id from attributeTranslation where attribute=a.id and language=1),
(select translation from attributeTranslation where attribute=a.id and language=1), 
from attribute a;

我希望能够从一个查询中获取id和翻译,所以我将列连接起来并稍后从字符串中获取id,这至少会产生单个子查询,但仍然看起来不正确。

select attribute,
(select concat(id,';',title)
    from offerAttribute_language 
    where offerAttribute=a.id and _language=1
)
from offerAttribute a

所以问题部分。 有没有办法从单个子查询中获取多个列,或者我应该使用两个子查询(mysql是否足够聪明,可以对它们进行分组?)或者加入以下方式:

[[语言的属性]到翻译](连接3个表似乎比子查询更差)。

1 个答案:

答案 0 :(得分:93)

是的,你可以这样做。您需要的诀窍是有两种方法可以从表服务器中获取表。一种方法是......

FROM TABLE A

另一种方式是

FROM (SELECT col as name1, col2 as name 2 FROM ...) B

请注意,select子句及其周围的括号一个表,一个虚拟表。

所以,使用你的第二个代码示例(我猜你希望在这里检索的列):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

请注意,您的真实表attribute是此联接中的第一个表,而我称为b的虚拟表是第二个表。

当虚拟表是某种汇总表时,这种技术特别方便。 e.g。

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

看看怎么样?您已生成包含两列的虚拟表c,将其连接到另外两列,使用ON子句中的一列,并将另一列作为结果集中的列返回。 / p>