Syntax SELECT EXISTS using MySql version 8.0.17

Hi, I need your appreciated help

In the table do_table stored an a database MySql version 8.0.17 I have these rows

+----+-------------------------+-----+
| ts | tt                      | tID |
+----+-------------------------+-----+
|  1 | t_contents_11111_2_2021 |   1 |
|  0 | t_contents_2222_2_2021  |   2 |
|  1 | t_contents_3333_2_2021  |   3 |
+----+-------------------------+-----+

Using SQL I need:

  1. Checking if table exists in the database because it may not have been created yet;
  2. And if ts field is equal to zero the return of @t it should be zero else the return of @t it should be one

SQL query below

mysql> SELECT EXISTS
    ( SELECT @t := tt, 
      CASE WHEN ts = 0 THEN 0 
      ELSE 1 END
      FROM `do_table` WHERE tt = 't_contents_2222_2_2021') AS COUNT INTO @t;
    
SELECT
    @t;
Query OK, 1 row affected (0.00 sec)

+----+
| @t |
+----+
|  1 |
+----+
1 row in set (0.01 sec)

The return of @t instead it’s always one … whatever row is getting …

-- ----------------------------
-- Table structure for do_table
-- ----------------------------
DROP TABLE IF EXISTS `do_table`;
CREATE TABLE `do_table`  (
  `ts` int(11) DEFAULT NULL,
  `tt` varchar(255) DEFAULT NULL,
  `tID` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`tID`) USING BTREE
) ENGINE = InnoDB;

-- ----------------------------
-- Records of do_table
-- ----------------------------
INSERT INTO `do_table` VALUES (1, 't_contents_11111_2_2021', 1);
INSERT INTO `do_table` VALUES (0, 't_contents_2222_2_2021', 2);
INSERT INTO `do_table` VALUES (1, 't_contents_3333_2_2021', 3);

well, sure

that’s because if it does find the row in your WHERE clause, then that row exists, and therefore @t must equal 1

try running the same query with WHERE tt = 'foo' and you will see @t becomes 0

1 Like

also i should point out that you seem to be using the same variable @t for two different purposes in that query

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.