Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

How to determine if a MySQL query is valid?

Look here and here.

With the answers above, I have made this query, is it valid? If not, how can I correct it?

SELECT *,
 FROM TABLE_2 t
 WHERE EXISTS(SELECT IF(column1 = 'smith', column2, column1)       
 FROM TABLE_1 a
 WHERE 'smith' IN (a.column1, a.column2)
        AND a.status = 1              
                AND ( 'smith' IN (t.column1, t.column2)
               )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To start with, the comma after select * does not belong.

Second, you alias your tables (table_2 t and table_1 a), but then you don't consistently use the aliases, so you might have issues at run time. Also from a maintenance perspective, I think most folks prefer to use aliases when declared, and no aliases otherwise.

Third, you do a comparison against cols from the t table in the outer select ('smith' in (t.column1, t.column2) ), when that appears unnecessary. You can just do it in the outer select. In other words, you can move that terminal paren to before the AND ('smith'...

As for whether it works -- I have no idea, since I don't know what you are trying to accomplish.

Combined, that would leave you with :

SELECT t.*
FROM TABLE_2 t
WHERE EXISTS (SELECT IF(a.column1 = 'smith', a.column2, a.column1)       
              FROM TABLE_1 a
              WHERE 'smith' IN (a.column1, a.column2)
              AND a.status = 1)
AND ( 'smith' IN (t.column1, t.column2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...