假设我有下表:
TABLE: product
===============================================================================
| product_id | language_id | name | description |
===============================================================================
| 1 | 1 | Widget 1 | Really nice widget. Buy it now! |
-------------------------------------------------------------------------------
| 1 | 2 | Lorem 1 | |
-------------------------------------------------------------------------------我如何查询它,使其尝试给出name和description,其中language_id = 2,但如果列包含NULL,则回退到language_id =1?
在上面的示例中,我应该为name获取Lorem 1,为description获取Really nice widget. Buy it now!。
发布于 2011-04-10 17:06:17
这个怎么样?
SET @pid := 1, @lid := 2;
SELECT
COALESCE(name,(
SELECT name
FROM product
WHERE product_id = @pid AND description IS NOT NULL
LIMIT 1
)) name,
COALESCE(description,(
SELECT description
FROM product
WHERE product_id = @pid AND description IS NOT NULL
LIMIT 1
)) description
FROM product
WHERE product_id = @pid
AND (language_id = @lid
OR language_id = 1)
ORDER BY language_id DESC
LIMIT 1;其中:
@pid:current product id@lid:current language id nulllanguage_id name和/或description的值可能为item =2 item and exist发布于 2011-04-10 07:59:07
select name, description from product
where product_id = @pid
and name is not null
and description is not null
and (language_id = @lang or language_id = 1)
order by language_id desc其中@pid是当前的产品id,@lang是当前的语言id。
返回的第一行将包含当前名称和描述。
这假设行language_id = 1的名称或描述中不包含NULL。
发布于 2011-04-10 07:59:17
select p2.product_id
,coalesce(p2.name, p1.name, 'No name') as name
,coalesce(p2.description, p1.description, 'No description') as description
from product p2
left join product p1 on(
p1.product_id = p2.product_id
and p1.language_id = 1
)
where p2.product_id = 1
and p2.language_id = 2;Edit1:
上面的查询假设language=2行存在,但名称/descr可能为null。
编辑2.
我记得最近有人问了一个类似的问题。然后我发现它是you。您需要将产品与翻译分开。这就是让这个查询难以编写的原因。Thomas answer使您可以轻松地执行您想要的操作。
https://stackoverflow.com/questions/5608740
复制相似问题