我在使用聚结和连接的同时遇到了困难。我的计划是:
虽然我的查询返回其正确的值,但在本例中,似乎忽略了空值。
venture_list表:
-------------------
| vid | name |
-------------------
| 1 | Malaysia |
-------------------
| 2 | Singapore |
-------------------request_forms:
---------------------------------------------
| fid | username | venture | venture_other |
---------------------------------------------
| 1 | jake.long | 2 | |
---------------------------------------------
| 2 | xander.f | 0 | Japan |
---------------------------------------------预期结果
---------------
| venturename |
---------------
| Singapore |
---------------
| Japan |
---------------实际结果
---------------
| venturename |
---------------
| Singapore |
---------------以下是我的查询:
SELECT COALESCE(NULLIF(ventures.name, null), venture_other) AS venturename
FROM request_forms forms
JOIN venture_list ventures ON ventures.vid = forms.venture我试着重新排列列名,但没有起作用。
发布于 2017-10-13 13:46:18
问题是,MySQL在JOIN上的默认行为是INNER JOIN。显然,由于venture_list中的第二行没有匹配结果,所以只能返回1行。
尝试使用LEFT JOIN,这样列ventures.name将导致NULL,因此将使用venture_other。
发布于 2017-10-13 13:43:01
您最初在这里使用NULLIF()是很奇怪的。从文件中:
如果expr1 = expr2为真,则返回NULL,否则返回expr1。
因此,您的声明说,“如果ventures.name为NULL,则返回NULL,否则返回ventures.name”。这是多余的,因为NULL已经返回NULL,因为它是NULL。
而不是使用NULLIF(),您可以让NULLIF()在ventures.name是0的情况下返回NULL
SELECT COALESCE(NULLIF(ventures.name, 0), venture_other) AS venturename
FROM request_forms forms
JOIN venture_list ventures ON ventures.vid = forms.venture发布于 2017-10-13 13:47:18
您已经非常接近了,但是需要稍微更改一下空值:
select coalesce(nullif(ventures.name,0), venture_other) as venturename
from request_forms forms
join venture_list ventures
on ventures.vid = forms.venture;基本上,如果ventures.name是0..then,则希望使用null f来使其空出,其余部分由合并完成。
https://stackoverflow.com/questions/46731223
复制相似问题