基本上有属性表和转换表 - 一个属性的许多翻译.
我需要为指定语言中的每个属性选择翻译的id和值,即使该语言中没有翻译记录.我错过了一些连接技术或连接(不涉及语言表)在这里不起作用,因为以下不返回具有指定语言的非现有翻译的属性.
select a.attribute, at.id, at.translation
from attribute a left join attributeTranslation at on a.id=at.attribute
where al.language=1;
Run Code Online (Sandbox Code Playgroud)
所以我使用这样的子查询,这里的问题是使用相同的参数对同一个表进行两个子查询(感觉就像性能耗尽,除非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;
Run Code Online (Sandbox Code Playgroud)
我希望能够从一个查询中获取id和翻译,所以我将列连接并稍后从字符串中获取id,这至少会产生单个子查询,但仍然看起来不正确.
select attribute,
(select concat(id,';',title)
from offerAttribute_language
where offerAttribute=a.id and _language=1
)
from offerAttribute a
Run Code Online (Sandbox Code Playgroud)
所以问题部分.有没有办法从单个子查询中获取多个列,或者我应该使用两个子查询(mysql是否足够聪明地将它们分组?)或者加入以下方式:
[[语言属性]到翻译](加入3个表似乎比子查询更差).
O. *_*nes 100
是的,你可以这样做.您需要的诀窍是有两种方法可以从表服务器中获取表.一种方法是......
FROM TABLE A
Run Code Online (Sandbox Code Playgroud)
另一种方式是
FROM (SELECT col as name1, col2 as name 2 FROM ...) B
Run Code Online (Sandbox Code Playgroud)
请注意,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)
Run Code Online (Sandbox Code Playgroud)
请注意,您的真实表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)
Run Code Online (Sandbox Code Playgroud)
看看怎么样?您已生成一个c包含两列的虚拟表,将其连接到另外两列,使用该ON子句的其中一列,并将另一列作为结果集中的列返回.