结果根据JOIN语法而改变

时间:2010-11-01 18:52:47

标签: sql mysql syntax join

也许我在这里有一个完整的细分,但是在给定相同字段的情况下JOIN ONJOIN USING不应该产生相同的结果?

e.g。

SELECT * FROM racks r join rack_positions p on (r.rack_id=p.rack_id);//46 rows
SELECT * FROM racks r join rack_positions p using (rack_id);//zero rows

那么为什么上述查询不会产生相同的结果呢? (我只是打赌我会因为没有搞清楚这一点而自责。)

CREATE TABLE语句

CREATE TABLE  `racks` (
  `rack_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `watersystem_id` int(10) unsigned NOT NULL,
  `pgroup_id` int(10) unsigned DEFAULT NULL,
  `rack_name` varchar(20) NOT NULL,
  `barcode_id` int(10) unsigned DEFAULT NULL,
  `row_max` int(10) unsigned NOT NULL DEFAULT '0',
  `spigot_max` int(10) unsigned NOT NULL DEFAULT '0',
  `added_by` int(10) unsigned DEFAULT NULL,
  `added_on` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `modded_by` int(10) unsigned DEFAULT NULL,
  `modded_on` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`rack_id`),
  UNIQUE KEY `watersystem_id` (`watersystem_id`,`rack_name`) USING BTREE,
  UNIQUE KEY `FK_racks_2` (`barcode_id`) USING BTREE,
  KEY `pgroup_id` (`pgroup_id`),
  CONSTRAINT `FK_racks_2` FOREIGN KEY (`barcode_id`) REFERENCES `barcodes` (`barcode_id`),
  CONSTRAINT `racks_ibfk_1` FOREIGN KEY (`watersystem_id`) REFERENCES `watersystems` (`watersystem_id`),
  CONSTRAINT `racks_ibfk_2` FOREIGN KEY (`pgroup_id`) REFERENCES `perm_groups` (`pgroup_id`) ON DELETE SET NULL
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;


CREATE TABLE  `rack_positions` (
  `pos_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `rack_id` int(10) unsigned NOT NULL,
  `row_num` tinyint(3) unsigned NOT NULL,
  `spigot_num` tinyint(3) unsigned NOT NULL,
  `operating` tinyint(1) DEFAULT '1' COMMENT 'set to false if location cannot be used',
  `notes` text COMMENT 'optional note about why a location might be non-operational',
  `barcode_id` int(10) unsigned DEFAULT NULL,
  `added_by` int(10) unsigned DEFAULT NULL,
  `added_on` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `modded_by` int(10) unsigned DEFAULT NULL,
  `modded_on` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`pos_id`),
  UNIQUE KEY `FK_locations_2` (`barcode_id`) USING BTREE,
  KEY `rack_id` (`rack_id`),
  KEY `FK_rack_positions_3` (`added_by`),
  KEY `FK_rack_positions_4` (`modded_by`),
  CONSTRAINT `FK_rack_positions_4` FOREIGN KEY (`modded_by`) REFERENCES `users` (`user_id`) ON DELETE SET NULL,
  CONSTRAINT `FK_locations_2` FOREIGN KEY (`barcode_id`) REFERENCES `barcodes` (`barcode_id`),
  CONSTRAINT `FK_rack_positions_3` FOREIGN KEY (`added_by`) REFERENCES `users` (`user_id`) ON DELETE SET NULL,
  CONSTRAINT `rack_positions_ibfk_1` FOREIGN KEY (`rack_id`) REFERENCES `racks` (`rack_id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=98 DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;

1 个答案:

答案 0 :(得分:0)

根据SQL-92,连接结果应该几乎相同。唯一的区别是USING语法应返回名为rack_id的第一列的结果,而ON语法应返回两个表中的rack_id列。