1

我正在尝试这样做

SELECT 
  table1.*,
  table2.id as t2id 
FROM 
  table1 as t1 
INNER JOIN table2 as t2 
  ON t2.field1 = t1.field2 
  AND t1.field2 = 'value'
  AND IF(SELECT COUNT(*) FROM table2 WHERE id = 10 > 0)

它错误说

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 

'SELECT COUNT(*) FROM table2 WHERE id = 10 > 0) LIMIT ' at line 1

我知道错误与 if 条件有关,因为当我删除它时,它可以工作,但我的想法是如果它不成功,select 将返回一个空值,即它没有在 table2 中找到 id 为 10 的表中的任何内容。

4

3 回答 3

1

你错过了如果的“那么”部分。

它看起来也像 IF(条件,然后,否则),但您只是在执行条件而没有任何输出。

试试这样:

AND IF((SELECT COUNT(*) FROM table2 WHERE id = 10) > 0, 'true', 'false')
于 2013-04-26T14:57:40.813 回答
1

尝试删除IF.

SELECT 
  table1.*,
  table2.id as t2id 
FROM 
  table1 as t1 
INNER JOIN table2 as t2 
  ON t2.field1 = t1.field2 
  AND t1.field2 = 'value'
  AND (SELECT COUNT(*) FROM table2 WHERE id = 10) > 0;
于 2013-04-26T15:05:52.213 回答
0

试试这个(确保你在同一个会话中执行查询):

SELECT COUNT(*) INTO @COUNTER FROM table2 WHERE id = 10 ;

SELECT 
  table1.*,
  table2.id as t2id 
FROM 
  table1 as t1 
INNER JOIN table2 as t2 
  ON t2.field1 = t1.field2 
  AND t1.field2 = 'value'
  AND @COUNTER > 0 ;
于 2013-04-26T14:58:00.300 回答