如果返回null,则左连接上的“on”的默认值

时间:2014-08-08 03:47:08

标签: mysql

这是我当前的查询无效

假设@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是默认

2 个答案:

答案 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')