MySQL 单查询双查询

MySQL double query in single query

我有两个 table:

CREATE TABLE folders (
ID BIGINT PRIMARY KEY AUTO_INCREMENT,
uid BIGINT NOT NULL,
driveid BIGINT NOT NULL,
foldername VARCHAR(64) NOT NULL,
icon_url varchar(260),
time_created timestamp NOT NULL default '0000-00-00 00:00:00',
time_updated timestamp NOT NULL default '0000-00-00 00:00:00' on update CURRENT_TIMESTAMP,
time_expires timestamp NOT NULL default '0000-00-00 00:00:00'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


CREATE TABLE drives (
ID BIGINT PRIMARY KEY AUTO_INCREMENT,
uid BIGINT NOT NULL,
drivename VARCHAR(100) NOT NULL,
icon_url varchar(260),
time_created timestamp NOT NULL default '0000-00-00 00:00:00',
time_updated timestamp NOT NULL default '0000-00-00 00:00:00' on update CURRENT_TIMESTAMP,
time_expires timestamp NOT NULL default '0000-00-00 00:00:00'

) ENGINE=MyISAM DEFAULT CHARSET=utf8;

我想要 select 驱动器和所有文件夹,其中:

  1. 在驱动器 table 中 uid = UID NUMBER
  2. 在文件夹中,其中 dbid = ID 来自也有 UID = given UID number
  3. 的驱动器

我想要单个查询并在单个响应中获得完整结果。可能吗? 如果是这样,请提出建议,我不想粘贴我尝试过的内容,因为它们很愚蠢,我尝试了内部连接、左连接、混合查询,但我没有接近。

我很确定您需要 union 查询。我不确定查询是什么,因为您的问题没有指定示例数据或所需的结果。例如,不清楚要比较哪个用户id。

但是,以下内容应该与您想要的非常接近:

select d.id as driveid, NULL as folderid
from drives d
where d.uid = @UID
union all
select d.id, f.id as folderid
from drives d join
     folders f
     on f.dbid = d.id
where f.uid = @UID;

最终,这相当于 LEFT JOIN 有两个条件。如果 uiddrives 中有记录但没有关联的文件夹,则驱动器将与文件夹列中的 NULL 一起返回。 driveid必须匹配drives.IDuid必须相同;这两个都将在 ON 子句中指定。

SELECT
  drives.ID AS driveid,
  drives.drivename,
  drives.uid,
  folders.ID AS folderid,
  folders.foldername,
  folders.icon_url,
  drives.time_created AS drive_time_created,
  drives.time_updated AS drive_time_updated,
  drives.time_expires AS drive_time_expires,
  folders.time_created AS folders_time_created,
  folders.time_updated AS folders_time_updated,
  folders.time_expires AS folders_time_expires
FROM
  drives
  LEFT JOIN folders
    ON drives.ID = folders.driveid
    AND drives.uid = folders.uid
WHERE
  drives.uid = [the-specified-uid]