SQL:选择具有条件优先级的随机行

时间:2017-11-29 12:06:45

标签: sql postgresql

我有条件,我想根据他们是否符合以下三个条件之一来选择随机用户:

  1. 如果匹配邮政编码
  2. 如果他们符合城市名称
  3. 如果匹配州名
  4. 如果匹配一个,则返回随机选择的结果。

    基本上是这样的(〜伪代码):

    SELECT * FROM user
    INNER JOIN address ON address.id = user.address_id
    WHERE address.zipcode = '00000' IF EXISTS ELSE (
        WHERE address.province = 'State Name' IF EXISTS ELSE
            (WHERE address.city = 'City Name')
    )
    ORDER BY RANDOM() LIMIT 1;
    

    有没有很好的方法可以做到这一点,还是将它分成三个单独的查询更容易?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要一个优先级,从邮政编码开始。如果是这样的话:

SELECT u.*
FROM user u INNER JOIN
     address a
     ON a.id = u.address_id
WHERE a.zipcode = '00000' OR
      a.province = 'State Name' OR
      a.city = 'City Name'
ORDER BY (a.zipcode = '00000')::INT DESC,
         (a.province = 'State Name')::INT DESC,
         (a.city = 'City Name')::INT DESC,
         random();
LIMIT 1;

如果您只想要三者中的任何一个匹配 - 并在其中随机选择 - 那么请使用ORDER BY random()

答案 1 :(得分:1)

我对你的问题有些怀疑,但如果我理解,这将解决:

将变量用于您的值并检查它是否为空

DECLARE @zipcode VARCHAR(8) = '12425190'
DECLARE @province VARCHAR(50) = 'São Paulo'
DECLARE @city VARCHAR(50) = 'Pindamonhangaba'

SELECT * FROM user
INNER JOIN address ON address.id = user.address_id
WHERE (@zipcode = null OR address.zipcode = @zipcode) &&
      (@province = null OR address.province = province) &&
      (@city = null OR address.city = @city)    
ORDER BY RANDOM() LIMIT 1;