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:
database
because it may not have been created yet;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);
For table creation, you can use IF NOT EXISTS
:
CREATE TABLE IF NOT EXISTS`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;
For the query, you can do:
SELECT IF(ts=0, 0, 1) INTO @t
FROM `do_table`
WHERE tt = 't_contents_2222_2_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.