繁体   English   中英

对于这种情况需要一个sql查询

[英]Need a sql query for this scenario

大家好,请帮助我为该情况连接一个SQL查询

+----+---------+--------+------------+--------------+
| ID | country | region | restaurant | locationcode |
+----+---------+--------+------------+--------------+
|  1 | IND     | DL     | xyz        |          100 |
|  2 | IND     | DL     | yzc        |          111 |
+----+---------+--------+------------+--------------+

选择所有项目-

if condition matched with country,region,restaurant,locationcode
  If not then all items that matched condition with country,region,restaurant
      if not then all items that matched the condition with country,region

我可以使用sql查询还是必须使用应用程序逻辑来处理?

这个解决方案有点冗长,但应该可以。 使用CASE从选项中进行选择,然后使用这些行的存在作为选择条件。

SELECT id FROM mytable WHERE 
CASE 
     WHEN EXISTS( SELECT 1 FROM mytable WHERE region='DL' AND country='IND'
                   AND restaurant='xyz' AND locationcode='100')
       THEN region='DL' AND country='IND' AND restaurant='xyz' AND locationcode='100'
     WHEN EXISTS( SELECT 1 FROM mytable WHERE region='DL' AND country='IND')
       THEN region='DL' AND country='IND'
     WHEN EXISTS( SELECT 1 FROM mytable WHERE region='DL' )
       THEN region = 'DL';
     END; 

可以使用IF这样实现

SELECT 
    * 
FROM mytable mt
WHERE
    IF(
        mt.region='DL' 
        AND mt.country='IND' 
        AND mt.restaurant='xyz' 
        AND mt.locationcode='100',
        1,
        IF(
            mt.region='DL' 
            AND mt.country='IND' 
            AND mt.restaurant='xyz',
            1,
            IF(
                mt.region='DL' 
                AND mt.country='IND'
            ,1,
            'Nothing Found')
        )
    )

我认为,如果我们想用SQL做,那么更好的方法是用SQL块做。

类似于此处给出的示例: https : //stackoverflow.com/a/11222053/555953

暂无
暂无

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

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