带子查询的SQL WHERE条件为空

时间:2018-05-28 06:47:25

标签: mysql sql subquery

我希望有人可以就错误提出建议。

SELECT sms.id FROM sms INNER JOIN screens ON sms.screen_id = screens.id WHERE screens.experience_id = '108';

SELECT id FROM sms
WHERE screen_id IN (SELECT id FROM screens WHERE experience_id = 108 )

...返回一个空行,但是应该返回行。

澄清......

SELECT id FROM sms

...返回SMS中的所有行

SELECT id FROM sms
WHERE screen_id IN (SELECT id FROM screens)

...返回SMS和

中的所有行
SELECT id FROM screens WHERE experience_id = 108

...从具有该ID的屏幕返回所有行。

制作表格的SQL ......

    CREATE TABLE IF NOT EXISTS `screens` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `device_id` int(11) NOT NULL,
  `type` varchar(32) NOT NULL,
  `description` text NOT NULL,
  `position` int(11) NOT NULL,
  `experience_id` int(11) NOT NULL,
  `image` varchar(512) NOT NULL,
  `url` varchar(512) NOT NULL,
  `persona_id` int(11) NOT NULL,
  `socialPost` text NOT NULL,
  `socialLinkHeadline` varchar(512) NOT NULL,
  `socialLinkDescription` text NOT NULL,
  `socialLink` varchar(512) NOT NULL,
  `socialAction` varchar(64) NOT NULL,
  `bgcolor` varchar(16) NOT NULL DEFAULT '#fff',
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `user_id` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=472 ;


CREATE TABLE IF NOT EXISTS `sms` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `source` varchar(16) NOT NULL,
  `content` text NOT NULL,
  `position` int(11) NOT NULL,
  `screen_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;

我运行这些查询以验证的GIF在这里:https://ibb.co/gzPFsd

我很茫然,可以看到人们无法复制,谢谢!

2 个答案:

答案 0 :(得分:0)

我的查询中没有错误,但您也可以使用加入。

SELECT sms.id FROM sms INNER JOIN screens ON sms.screen_id = screens.id WHERE screens.experience_id = '108';

答案 1 :(得分:0)

您的查询工作正常,这是证明。

DROP TABLE IF EXISTS SMS,SCREENS;
CREATE TABLE SMS(ID INT, SCREEN_ID INT);
CREATE TABLE SCREENS(ID INT, EXPERIENCE_ID INT);

INSERT INTO SMS VALUES (1,1),(2,2);
INSERT INTO SCREENS VALUES(1,108),(2,100);

SELECT id FROM sms
WHERE screen_id IN (SELECT id FROM screens WHERE experience_id = 108 );

+------+
| id   |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

假设我的数据模型与您的数据模型相同。