在 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个表似乎比子查询的性能更差)。

181368 次浏览

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

FROM TABLE A

另一种方式是

FROM (SELECT col as name1, col2 as name2 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的这个虚表是第二个表。

当虚拟表是某种形式的汇总表时,这种技术特别方便。

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子句,并将另一列作为结果集中的列返回。