Running the following scripts, you will get 2 tables with records.
-- ----------------------------
-- Table structure for data
-- ----------------------------
DROP TABLE IF EXISTS `data`;
CREATE TABLE `data` (
`id` int(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of data
-- ----------------------------
INSERT INTO `data` VALUES ('1');
INSERT INTO `data` VALUES ('2');
-- ----------------------------
-- Table structure for status
-- ----------------------------
DROP TABLE IF EXISTS `status`;
CREATE TABLE `status` (
`id` int(255) DEFAULT NULL,
`status` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of status
-- ----------------------------
INSERT INTO `status` VALUES ('1', '0');
INSERT INTO `status` VALUES ('1', '1');
Table data
+--------+--------+
| id | more...|
|--------|--------+
| 1 | |
| 2 | |
+--------+--------+
Table status
+--------+--------+
| id | status |
|--------|--------+
| 1 | 0 |
| 1 | 1 |
+--------+--------+
I need select data of table data
excluded items which status is 0 after refer to status
.
Wrong try 1
I write the following SQL, and get the following result. It's not the expected result because the item id=2 is also needed.
select * from data d LEFT JOIN status s on d.id=s.id where s.status=1
+--------+--------+--------+
| id | id1 | status |
|--------|--------|--------+
| 1 | 1 | 1 |
+--------+--------+--------+
Wrong try 2
Then I change where
to on
, and get the following result which looks good.
select * from data d LEFT JOIN status s on d.id=s.id and s.status=1
+--------+--------+--------+
| id | id1 | status |
|--------|--------|--------+
| 1 | 1 | 1 |
+--------+--------+--------+
| 2 | (Null) | (Null) |
+--------+--------+--------+
Try 3
Table status
has two items now. If I delete the item (id=1,status=1) of table status
, what will be the result ?
select * from data d LEFT JOIN status s on d.id=s.id and s.status=1
+--------+--------+--------+
| id | id1 | status |
|--------|--------|--------+
| 1 | (Null) | (Null) |
+--------+--------+--------+
| 2 | (Null) | (Null) |
+--------+--------+--------+
In this case, I expect the item id=1 should not be here . The expected result is
+--------+--------+--------+
| id | id1 | status |
+--------+--------+--------+
| 2 | (Null) | (Null) |
+--------+--------+--------+
Why does the item id=1 appear in the result ? Can't it resolve my issue using on status=1
?