简体   繁体   English

SQL使用后备列进行匹配

[英]SQL using fallback column for match

Say I have a table in an sql database like 假设我在sql数据库中有一张表,例如

name    age  shoesize
---------------------
tom      20      NULL
dick   NULL         4
harry    30         5

and I want an SQL statement that selects names that have age == X, or as a fallback, if no such names exist, use those with shoe size == Y. In other words, in this table, for X=20,Y=4 I should only get 'tom', while for X=25,Y=4 I should get only 'dick'. 并且我想要一个SQL语句,该语句选择使用年龄== X的名称,或者作为备用,如果不存在这样的名称,请使用鞋号== Y的名称。换句话说,在此表中,对于X = 20,Y = 4我应该只得到'tom',而对于X = 25,Y = 4我应该只得到'dick'。 I can't do that with 我不能这样做

SELECT name FROM table WHERE age = 20 OR shoe size = 4;

because that will select both tom and dick. 因为那样会同时选择tom和dick。 I'm currently using 我目前正在使用

SELECT COALESCE ((SELECT name FROM tab WHERE age = 20),(SELECT name FROM tab WHERE shoesize = 4));

but is there a neater way? 但是有更整洁的方法吗? Also using coalesce like this doesn't allow me to get the whole row - ie I can't use SELECT * FROM tab , I can only select a single name. 同样使用这样的合并不允许我得到整行-即我不能使用SELECT * FROM tab ,我只能选择一个名称。

You can use ORDER BY and FETCH FIRST 1 ROW ONLY or some similar clause: 您可以使用ORDER BYFETCH FIRST 1 ROW ONLY或类似的子句:

SELECT name
FROM tab
ORDER BY (CASE WHEN age = X THEN 1
               WHEN shoesize = Y THEN 2
               ELSE 3
          END)
FETCH FIRST 1 ROW ONLY;

Some databases spell FETCH FIRST 1 ROW ONLY like LIMIT or TOP or even something else. 一些数据库FETCH FIRST 1 ROW ONLYLIMITTOP甚至其他东西拼写FETCH FIRST 1 ROW ONLY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM