简体   繁体   中英

Check if a row exists using MySQL 8 version

I have this query in MySQL database 8.0.12 version

mysql> SELECT tTbl INTO @tTbl FROM t_table WHERE tTbl = "t_contents_1_2021";

SELECT @tTbl;
Query OK, 1 row affected (0.07 sec)

+-------------------+
| @tTbl             |
+-------------------+
| t_contents_1_2021 |
+-------------------+
1 row in set (0.07 sec) 

Now I need test whether a row exists in a MySQL table or not, using exists condition.

The exists condition can be used with subquery.

It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

I have tried without success

mysql> SELECT EXISTS(SELECT tTbl INTO @tTbl FROM t_table 
                 WHERE tTbl = "t_contents_1_2021");
1064 - 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 tTbl INTO @tTbl FROM t_table
                 WHERE tTbl' at line 1
mysql> 

How to do resolve this?

SELECT.. INTO does not return the rowset. EXISTS needs in rowset. So SELECT.. INTO cannot be used in EXISTS .

Remove it:

SELECT EXISTS ( SELECT tTbl 
                FROM t_table 
                WHERE tTbl = "t_contents_1_2021" );

If you need both check the row existence and save the value to the variable then use inline assigning:

SELECT EXISTS ( SELECT NULL
                FROM t_table 
                WHERE (@tTbl := tTbl) = "t_contents_1_2021" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM