2016-12-01 9 views
0

(konnte nicht denken Sie an einen sehr guten Titel für diese)SQL-Anweisung bedingte Spaltung Ergebnis verrohrt ergab basierend auf bedingte

sagen, dass ich eine Tabelle als

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 | 
+-------------+--------------+------+-----+---------+ 

folgt würde Ich mag abfragen basierend auf Namen, dann aus den Ergebnissen, greift die Namen zur Vereinigung von Bedeutung, wenn es vorhanden ist, andernfalls

Beispiel der Zeile mit NULL für die Assoziation greifen:

association = 'hello'; 
results = query('SELECT * FROM accts WHERE name = "world"'); 

/* 
results = [ 
    { name: 'hello', association: null }, 
    { name: 'hello', association: 'earth' }, 
    { name: 'hello', association: 'world' }, 
] 
*/ 

// here I want to grab the row where association matches, 
// but default to association = NULL if none exists 
// (the psuedo code below describes it programmatically) 

default = null 
for result in results 
    if not result.association 
     default = result 
    else if result.association equals association 
     return result 

return default 

Es ist einfach, mit Code zu schreiben, aber ich würde es vorziehen, dies in eine SQL-Anweisung zu verpacken, kann jemand helfen?

Antwort

1

Ich glaube, Sie so etwas wie dies wollen:

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

Oder alternativ:

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) 
+0

perfekt, danke! Ich ging mit Option 1 – Jeremy

Verwandte Themen