需要针对此方案的SQL查询

时间:2014-08-22 06:49:46

标签: mysql sql sql-server

大家好,请帮我为场景连接一个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查询执行此操作,还是必须使用应用程序逻辑来处理它?<​​/ p>

3 个答案:

答案 0 :(得分:1)

这个解决方案有点冗长,但应该有效。使用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; 

答案 1 :(得分:1)

可以使用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')
        )
    )

答案 2 :(得分:0)

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

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

相关问题