mysql - 这个场景需要一个sql查询

标签 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>

最佳答案

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

关于mysql - 这个场景需要一个sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25441133/

相关文章:

mysql - 如何用另一个数据表中的数据更新空数据表

mysql - 如何获得mysql中两个表之间的比较差异列值

python - 查询 Django 模型时,有没有办法匹配字段中的每个字符串

sql - 如何将事务隔离级别设置为用户的默认未提交读

c# - 使用 Visual Studio 在运行时创建本地数据库

php - 用户登录codeigniter后获取数据

c# - 间歇性System.ComponentModel.Win32Exception : The network path was not found

sql - 甲骨文 12c : How can I modify an existing primary key column to an identity column?

sql-server - 如何在 SQL Server 2008 中创建序列

sql - 为什么在SQL Server 中使用XML 类型来存储XML 数据?