如果找不到,如何编写sql查询以选择其他

时间:2017-09-22 06:06:54

标签: mysql database postgresql

我在表中有记录,其值在destinationcountryid字段中,如638,101和-1。 -1是默认值,如果没有匹配,则select query应返回此记录。

我在下面写了sql查询。

SELECT
  externalid
FROM
  mLookup.Addon_Spec_Tbl
WHERE
  productid = 30046 AND keyid = 2 AND countryid = 638 AND clientid = 10018 AND subkeyid = 4 AND destinationcountryid IN(302,
  -1)
ORDER BY
  id DESC
LIMIT 1

我在这里得不到正确的结果。 我的表架构如下

CREATE TABLE spec_tbl(
  id SERIAL NOT NULL,
  productid INTEGER NOT NULL,
  keyid INTEGER,
  subkeyid INTEGER,
  externalid CHARACTER VARYING(100),
  countryid INTEGER,
  destinationcountryid INTEGER,
  originid INTEGER,
  destinationid INTEGER,
  clientid INTEGER,
  categoryid INTEGER,
  created TIMESTAMP WITHOUT TIME zone DEFAULT NOW(), 
  modified TIMESTAMP WITHOUT TIME zone DEFAULT NOW(), 
  enabled BOOLEAN DEFAULT TRUE, 
  CONSTRAINT spec_tbl_pkey PRIMARY KEY(id))

示例插入

INSERT INTO spec_tbl(
productid, keyid, subkeyid, externalid, countryid, destinationcountryid, originid, destinationid, clientid, categoryid, remarks)
VALUES
(30046, 2, 4   , 'ABC', 638, 603, NULL, NULL, 10018, 25,'International Round Trip(include India) One Way Trip'),
(30046, 2, 4   , 'LMP', 638, 302, NULL, NULL, 10018, 25,'International Round Trip(include Bangladesh) One Way Trip'),
(30046, 2, 4   , 'KJP', 638, 208, NULL, NULL, 10018, 25,'International Round Trip(include Cuba) One Way Trip')
(30046, 2, 4   , 'XYZ', 638, -1, NULL, NULL, 10018, 25,'International Round Trip'),
;

我得到了回复但是它的destinationcountryid = -1的返回记录。 但是匹配目前destinationcountryid = 302.我希望这成为结果。

1 个答案:

答案 0 :(得分:0)

我认为你想要的逻辑是,如果当前查询成功匹配记录,则返回该记录的外部id值,否则返回-1。我们可以通过将您的查询放入CTE来模拟此行为。然后,将该查询与一个返回-1的查询联合起来,该查询仅在CTE没有返回记录时触发。

WITH cte AS (
    SELECT externalid
    FROM Spec_Tbl
    WHERE
        productid = 30046 AND
        keyid = 2 AND
        countryid = 638 AND
        clientid = 10018 AND
        subkeyid = 4 AND
        destinationcountryid = 302
    ORDER BY id DESC
    LIMIT 1
)

SELECT externalid::int
FROM cte
UNION ALL
SELECT -1
WHERE (SELECT COUNT(*) FROM cte) = 0;