如果前一个返回空字符串,是否有办法使用不同的WHERE子句选择rpd.name?
我调查了CASE,但我不确定如何使用它。
part_id href
1 url_1
2 url_2
3 url_3
part_id language_id 名称
1 2
1 1软管
2 2
2 1控制模块
3 2 vonkajsi kryt
3 1外壳
part_id href 名称
1 url_1软管
2 url_2控制模块
3 url_3 vonkajsi kryt
SELECT *
FROM replacement_part AS rp
LEFT JOIN replacement_part_description AS rpd
ON (rp.part_id = rpd.part_id)
WHERE language_id = :id
类似
if rpd.name = ''
WHERE language_id = a,
else
WHERE language_id = b
答案 0 :(得分:1)
这个?
SELECT *
FROM replacement_part AS rp
LEFT JOIN replacement_part_description AS rpd
ON (rp.part_id = rpd.part_id)
WHERE
(
language_id = :id
AND (rpd.name = '' OR rpd.name IS NULL)
)
OR language_id = b
答案 1 :(得分:0)
您可以使用order by
和limit
获得一行优先级:
select . . .
from . . .
where (language_id = a and rpd.name = '') or
language_id = b
order by (language_id = a) desc -- put the "a" rows first
limit 1;
答案 2 :(得分:0)
一种方法是两次加入rpd表,在ON条件上移动where子句,然后使用COALESCE:
SELECT
...,
COALESCE(rpd1.name, rpd2.name) AS name
FROM
replacement_part rp LEFT JOIN replacement_part_description rpd1
ON rp.part_id = rpd1.part_id AND rpd1.language=a
LEFT JOIN replacement_part_description rpd2
ON rp.part_id = prd2.part_id AND rpd2.language=b
这里我假设语言在描述表上。如果name是一个空字符串,而不是合并,则可以使用CASE WHEN:
CASE WHEN rpd1.name='' OR rpd1.name IS NULL THEN rpd2.name ELSE rpd1.name END AS Name