我试图这样做
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条件一样,当我删除它,它的工作原理,但我的想法是如果它不成功,选择将返回一个空值,即它没有找到表格中id为10的表格中的任何内容
任何帮助将不胜感激的家伙:)
答案 0 :(得分:1)
你错过了if。的“then”部分。
它看起来像IF(条件,然后,否则),但你只是在没有任何输出的情况下做这个条件。
以这种方式尝试:
AND IF((SELECT COUNT(*) FROM table2 WHERE id = 10) > 0, 'true', 'false')
答案 1 :(得分: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;
答案 2 :(得分: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 ;