0

Two tables:

prefix ( id, value )
---------------------
1  'hello'
2  'good afternoon'
3  'good night'


suffix ( id, value )
---------------------
1  'world'
3  'world'

I'd like to get all from table prefix which can be joined on table suffix via id

result should look like:

prefix.id  prefix.value   
--------------------------
1          'hello'        
3          'good night'   

well - quite easy so far... but if table suffix is empty I'd like everything from table prefix without subselects/ctes or if.... and in one query fulfilling both conditions! Is there any trick to get this done by some magic having-clause or tricky something else?

Just for testcases: SQL-fiddle

4

3 回答 3

3

好吧,有一种方法,但我同意其他人的观点,即您的要求没有(实际)意义。

无论如何,给你:

  1. 加入suffix表两次(每次都使用左连接)。一个连接在id列上,另一个连接在始终为真的条件下。

  2. 将结果分组到prefix输出中所需的列以及suffix.

  3. 在 HAVING 子句中,设置第一suffix列不为空或第二个实例中不可为空列的值的数量suffix为 0 的条件。(显然,每个组将具有相同的行数,即计数将每一prefix行都一样。)

这是查询:

SELECT prefix.id, prefix.value
FROM prefix
LEFT JOIN suffix ON prefix.id = suffix.id
LEFT JOIN suffix AS test ON 1=1
GROUP BY prefix.id, prefix.value, suffix.id
HAVING suffix.id IS NOT NULL OR COUNT(test.id) = 0;

SQL Fiddle上还有一个演示。

于 2013-07-23T17:26:22.770 回答
2

你需要一个ORNOT EXISTS

SELECT 
   prefix.id, prefix.value
FROM
   prefix 
WHERE 
   EXISTS(SELECT 1 from suffix WHERE prefix.id=suffix.id)
   OR NOT EXISTS(SELECT 1 FROM suffix)

演示

于 2013-07-23T13:57:12.903 回答
0

我想答案是:不,你不能!

或者如果你可以:不,你不应该。

于 2013-07-23T14:33:53.650 回答