我正在尝试从非统一表中选择UNIQUE值,并仅显示唯一值。
SELECT DISTINCT "year" as sorter, year(data) as year, NULL as location
FROM site
WHERE tipo='projects'
UNION
SELECT DISTINCT "loc" as sorter, NULL as year, spare_1 as location
FROM site
WHERE tipo='projects'
ORDER BY sorter ASC, year DESC, localition ASC
这将返回
+--------+------+----------+
| SORTER | YEAR | LOCATION |
+--------+------+----------+
| year | 2010 | NULL |
+--------------------------+
| year | 2009 | NULL |
+--------------------------+
| year | 2008 | NULL |
+--------------------------+
| loc | NULL | London |
+--------------------------+
| loc | NULL | Paris |
+--------------------------+
| loc | NULL | NYC |
+--------------------------+
我真的不喜欢双重选择。无论如何,我能做到这一点更有效率吗?
提前谢谢。
答案 0 :(得分:1)
我认为此查询可能适合您。
SELECT DISTINCT
CASE WHEN data IS NOT NULL THEN "year" ELSE "loc" END AS sorter,
CASE WHEN data IS NOT NULL THEN YEAR(data) ELSE NULL END AS year,
CASE WHEN data IS NULL THEN spare_1 ELSE NULL END AS location
FROM site
WHERE tipo='projects'
ORDER BY sorter ASC, year DESC, localition ASC
ORDER BY
子句似乎与您的示例数据不匹配,因此我保持不变。