我有下表
id site_id language_id paragraph
1 1 1 french text
2 1 2 english text
3 2 1 french text
4 2 3 spanish text
我想让查询返回段落给出site_id language_id,如:
SELECT paragraph FROM mytable WHERE site_id = givenSite AND
language_id =
if exists language_id = givenLanguage then givenLanguage
else if exists language_id = 2 then 2
else 1
我的工作方式如下,但我希望我们能写出更好的查询:
DECLARE @site int, $language int
SET @site = 1
SET @language = 3
SELECT CASE
WHEN EXISTS(SELECT paragraph_0
FROM tablename
WHERE language_id = @language AND site_id = @site)
THEN (SELECT paragraph_0
FROM tablename
WHERE language_id = @language AND site_id = @site)
ELSE (
SELECT CASE
WHEN EXISTS(SELECT paragraph_0
FROM tablename
WHERE language_id = 2 AND site_id = @site)
THEN (SELECT paragraph_0
FROM tablename
WHERE language_id = 2 AND site_id = @site)
ELSE (SELECT paragraph_0
FROM tablename
WHERE language_id = 1 AND site_id = @site)
END)
END
我试着写here但对不起,我不明白如何在sqlfiddle中声明变量。
答案 0 :(得分:0)
我认为这对你有用:
SELECT paragraph_0, IF(language_id = givenLanguage, 1, 0) AS isGivenLanguage
FROM tablename
WHERE site_id = 3 AND language_id IN (1, 2, givenLanguage)
ORDER BY isGivenLanguage DESC, language_id DESC
LIMIT 1
答案 1 :(得分:0)
这是一种方式。
require(["js/rsvp", "bootstrap"], function (RSVP) {
http://sqlfiddle.com/#!2/1c5fd4/20
更好地使用耙系统
set @site := 1 ;
set @language := 3 ;
select
language_id,paragraph_0 from (
select language_id,paragraph_0 from tablename where site_id =@site and language_id = @language
union
select language_id,paragraph_0 from tablename where site_id =@site and language_id <> @language
)x
order by language_id desc limit 1;
http://sqlfiddle.com/#!2/1c5fd4/24
来自评论
例如,如果我正在寻找网站3的语言5.如搜索 语言不存在它应该寻找英语,但英语不是 存在它应该返回强制存在的法语
这将非常简单,如下所示,看起来你已经明白了。
set @site := 1 ;
set @language := 3 ;
select
rank,paragraph_0 from (
select 0 as rank, paragraph_0 from tablename where site_id =@site and language_id = @language
union
select rank,paragraph_0 from(
select @rn:= @rn+1 as rank ,paragraph_0 , language_id
from tablename,(select @rn:=0)x where site_id =@site and language_id <> @language
order by language_id desc
)x
)x
order by rank limit 1;