这是我当前的查询无效
假设@value
是动态的
SELECT * FROM item as items
left join item_detail as details on items.id = details.item_id
and (details.language_id = @value or details.language_id = '1')
我要做的是,当@value
没有details.language_id
或者它返回null时,它应该保持连接值1
*更新
@value = 2
时,这应该是查询的可能结果
+------+------------------+-------------+
| item_name | language_id | description |
|-----------+-------------+-------------+
| Umbrella | 2 | とても良い |
| Belt | 1 | very sturdy |
+-----------+-------------+-------------+
不
+------+------------------+-------------+
| item_name | language_id | description |
|-----------+-------------+-------------+
| Umbrella | 2 | とても良い |
| Belt | null | null |
+-----------+-------------+-------------+
这意味着belt
没有item_detail
language_id = 2
,但language_id = 1
是默认
答案 0 :(得分:0)
使用COALESCE
默认为您想要的值,如下所示:
SELECT
items.item_name,
coalesce
(item_id,
(select item_id from item_detail d
inner join item i on d.item_id = i.id
where language_id = 1 limit 1)
) item_id,
coalesce
(description,
(select item_id from item_detail d
inner join item i on d.item_id = i.id
where language_id = 1 limit 1)
) description
FROM item as items
left join item_detail as details on items.id = details.item_id
and (details.language_id = @Value)
LEFT JOIN
会将字段返回NULL,无法找到匹配项。因此,我们需要将相关字段默认为所需的值。我们通过查询INNER JOIN
的{{1}}默认值为language_id
来执行此操作,因为每个项目都保证存在此值。
答案 1 :(得分:0)
我想我已经找到了你的问题
请问您可以尝试下面的SQL,并告诉我它是否适合您
SELECT * FROM item AS items
LEFT JOIN item_detail AS details
ON items.id = details.item_id
WHERE (details.language_id = COALESCE((SELECT language_id FROM item_detail WHERE language_id= @VALUE ),'1')