测试值存在,并相应地返回布尔值

时间:2019-10-24 14:02:49

标签: sql postgresql

我是SQL的新手,我一直在努力获得想要的结果。

我有这些表:

3 tables

我的目标是产生这个:

expected output

出于翻译目的:emprunt ==借用,livre ==书籍,全部==收藏

所以我的目标是获取所有书籍的id(id_livre),它们的藏书名(titre)和一个布尔值:
如果是借用则为TRUE(emprunt表中的id_livre)
否则为

我已经做到了:

SELECT livre.id_livre, titre, id_emprunt
FROM livre NATURAL JOIN oeuvre LEFT JOIN emprunt ON livre.id_livre = emprunt.id_livre
ORDER BY id_livre;

并获得以下输出:

Output I have so far

所以我接近我想要的,但是我不知道如何在第三列中进行返回布尔值而不是id_emprunt的测试

任何帮助表示感谢,谢谢。

3 个答案:

答案 0 :(得分:0)

您的代码与您所说的非常接近。您可以在第三列上使用CASE语句,根据t的值将输出更改为fid_emprunt

SELECT livre.id_livre,
       titre,
       CASE
         WHEN id_emprunt IS NULL THEN 'f'
         ELSE 't'
       END AS est_emprunte
  FROM livre NATURAL JOIN oeuvre LEFT JOIN emprunt ON livre.id_livre = emprunt.id_livre
  ORDER BY id_livre;

答案 1 :(得分:0)

只需使用#Get input [System.String]$SearchPath = Read-Host -Prompt 'Enter path' [System.String]$SearchPattern = Read-Host -Prompt 'Enter search pattern' [System.String]$SearchRecurse = Read-Host -Prompt 'Search recurse (Y/N)' #Validate input if ((-not $SearchPath) -or (-not (Test-Path -Path $SearchPath))) { throw ('Path "' + $SearchPath + 'is not available!') } if ((-not $SearchPattern)) { throw ('Search pattern is empty!') } if (('Y', 'N') -notcontains $SearchRecurse) { throw ('Search recurse parameter "' + $SearchRecurse + ' is not valid!') } #Get all files Out-Host -InputObject 'Get all files...' [PSCustomObject[]]$Files = @() if ($SearchRecurse -eq 'Y') { $Files = Get-ChildItem -Path $SearchPath -File -Recurse -Force #Collect also files from subfolders } else { $Files = Get-ChildItem -Path $SearchPath -File -Force #Collect only files from the current folder } #Search for string Out-Host -InputObject 'Search for string...' [PSCustomObject[]]$Output = @() foreach ($File in ($Files)) #Process each file { Out-Host -InputObject $File.FullName $Output += Select-String -Path $File.FullName -Pattern $SearchPattern | Select-Object -Property LineNumber, Filename, Path, Pattern, Line } $Output | Format-Table -Wrap 表达式:

case

Oracle没有内置的布尔类型,因此您可以使用字母SELECT l.id_livre, l.titre, (CASE WHEN e.id_emprunt IS NOT NULL THEN 't' ELSE 'f' END) as est_emprunte FROM livre l JOIN oeuvre o USING (id_livre) LEFT JOIN emprunt e USING (id_livre) ORDER BY id_livre; 't'。如果这样做(某些数据库可以这样做),您将使用:

'f'

请注意,我替换了 (e.id_emprunt IS NOT NULL) as est_emprunte 。我用“憎恶”一词来形容(部分与“自然”一词不适当)。我强烈反对使用它的原因是因为它没有考虑正确声明的外键关系。这也是很危险的,因为用于联接的列在查询中不明确,因此出于这个原因,我认为这也是一种不好的做法。

答案 2 :(得分:0)

您只需要使用CASE。所以:

SELECT livre.id_livre
       , titre
       , CASE WHEN id_emprunt IS NULL THEN 'f'
         ELSE 't' END AS est_emprunte 
FROM livre 
LEFT JOIN oeuvre 
USING(id_oeuvre)
LEFT JOIN emprunt 
USING(id_livre)
ORDER BY id_livre
相关问题