具有嵌套子查询的MySQL性能

时间:2018-02-14 22:38:59

标签: mysql

我有两个表消息和成员。我尝试连接表而没有嵌套查询,但它不反映成员的连接。所以,我最初认为我可以做以下

SELECT M1.*, COUNT(M2.emid) AS replies FROM messages M1
LEFT JOIN messages M2 
    ON M2.thread = M1.emid
INNER JOIN members M 
    ON M.meid = M1.emitter
WHERE 
    M1.thread is NULL AND 
    M1.receiver = 2
GROUP BY 
    M1.emid

但它似乎没有加入相应的成员。然后我尝试了这个,它给了我需要的结果,但我想知道是否有一种方法可以使用没有嵌套查询的连接来实现相同的结果

SELECT * FROM (
    SELECT M1.*, COUNT(M2.emid) AS replies FROM messages M1
    LEFT JOIN messages M2 
        ON M2.thread = M1.emid
    WHERE 
        M1.thread is NULL AND 
        M1.receiver = 2
    GROUP BY 
        M1.emid
) O INNER JOIN members M ON O.receiver = M.meid

- 表members

的表结构
CREATE TABLE `members` (
  `meid` bigint(64) NOT NULL,
  `name` varchar(32) DEFAULT NULL,
  `lastname` varchar(32) DEFAULT NULL,
  `email` varchar(128) NOT NULL,
  `mobile` char(10) DEFAULT NULL,
  `college` bigint(64) NOT NULL,
  `major` bigint(64) NOT NULL,
  `password` varchar(256) NOT NULL,
  `oauth` varchar(128) DEFAULT NULL,
  `confirmed` tinyint(4) DEFAULT NULL,
  `active` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `joined` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

- 表messages

的表结构
CREATE TABLE `messages` (
  `emid` bigint(20) NOT NULL,
  `emitter` bigint(20) NOT NULL,
  `receiver` bigint(20) NOT NULL,
  `thread` bigint(20) DEFAULT NULL,
  `opened` tinyint(4) DEFAULT '0',
  `message` blob NOT NULL,
  `timecard` datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

0 个答案:

没有答案