管道传递给基于条件的条件分割结果的SQL语句

时间:2016-12-01 14:23:42

标签: mysql sql

(无法想到一个非常好的标题)

说我有一张表如下

buttons: [
       {
           extend: 'pdf',           
           exportOptions: {
                columns: [1,2,3,4] // indexes of the columns that should be printed,
            }                      // Exclude indexes that you don't want to print.
       },
       {
           extend: 'csv',
           exportOptions: {
                columns: [1,2,3,4] 
            }

       },
       {
           extend: 'excel',
           exportOptions: {
                columns: [1,2,3,4] 
            }
       }         
    ]  

我想根据名称进行查询,然后从结果中获取与关联相关的名称(如果存在),否则,抓取CREATE TABLE IF NOT EXISTS accts ( name varchar(255) NOT NULL, association varchar(255) NULL, type varchar(255) NOT NULL, UNIQUE (name, association) ) ENGINE=InnoDB; mysql> desc accts; +-------------+--------------+------+-----+---------+ | Field | Type | Null | Key | Default | +-------------+--------------+------+-----+---------+ | name | varchar(255) | NO | MUL | NULL | | association | varchar(255) | YES | | NULL | | type | varchar(255) | NO | | NULL | +-------------+--------------+------+-----+---------+ 的行进行关联

示例:

NULL

使用代码编写很简单,但我更愿意将其包装成SQL语句,任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我想你想要这样的东西:

SELECT *
FROM accts
WHERE name = 'world' AND (assocation = 'hello' or association IS NULL)
ORDER BY (association IS NOT NULL) DESC
LIMIT 1;

或者,或者:

SELECT a.*
FROM accts a
WHERE name = 'world' AND assocation = 'hello' 
UNION ALL
SELECT a.*
FROM accts a
WHERE name = 'world' AND association IS NULL AND
      NOT EXISTS (SELECT 1 FROM accts a2 WHERE a2.name = a.name)