从2个表中获取数据(MySQL)

时间:2012-11-03 09:06:51

标签: mysql

我有2个具有相同列的表,我需要从两个表中显示它们,但现在我得到每行中的所有列,例如。定位器每行2次,它必须从正确的表中只显示1。

SELECT a.*, b.* FROM  clothes a, items b group by a.locator,b.locator

我该怎么做?

我将从两个表中输出行。 “name”,“locator”,“price”和WHERE“ibutik”= 1。

带有测试行的衣服表:

   CREATE TABLE IF NOT EXISTS `clothes` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `locator` varchar(48) DEFAULT NULL,
   `name` varchar(32) DEFAULT NULL,
     `price` int(11) DEFAULT '100',
    `level` smallint(6) DEFAULT '0',
     `type` smallint(6) DEFAULT NULL,
     `sex` smallint(4) DEFAULT NULL,
     `x_offset` smallint(6) DEFAULT '0',
     `y_offset` smallint(6) DEFAULT '0',
     `nontradeable` tinyint(4) DEFAULT '0',
     `ibutik` int(1) NOT NULL,
     `koebt` int(9) NOT NULL,
     PRIMARY KEY (`id`)
   ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=55 ;


 INSERT INTO `clothes` (`id`, `locator`, `name`, `price`, `level`, `type`, `sex`, `x_offset`, `y_offset`, `nontradeable`, `ibutik`, `koebt`) VALUES
   (1, '1.png', 'Male body', 100, 1, 2, 1, 0, 0, 0, 0, 0),
   (3, '1.png', 'Female body\r\n', 100, 1, 1, 2, 0, 0, 0, 0, 0))

和项目:

CREATE TABLE IF NOT EXISTS `items` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
  `locator` varchar(32) DEFAULT '',
  `name` varchar(32) DEFAULT '',
  `price` int(11) DEFAULT '100',
  `level` smallint(6) DEFAULT '0',
  `rotateable` tinyint(4) DEFAULT '0',
  `x_offset` smallint(6) DEFAULT '0',
  `y_offset` smallint(6) DEFAULT '0',
  `z_index` smallint(6) DEFAULT '0',
  `nontradeable` tinyint(4) DEFAULT '0',
  `ibutik` int(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;



INSERT INTO `items` (`id`, `locator`, `name`, `price`, `level`, `rotateable`, `x_offset`, `y_offset`, `z_index`, `nontradeable`, `ibutik`) VALUES
(1, 'rodplante.png', 'Rød plante', 10, 0, 0, 0, 0, 0, 0, 1),
(2, '1.png', 'Gul plante', 0, 0, 0, 0, 0, 0, 0, 0),
(3, '2.png', 'Gul plante', 0, 0, 0, 0, 0, 0, 0, 0),

1 个答案:

答案 0 :(得分:1)

可以尝试类似的事情:

select id,locator,name,price, tableName from 
(
  select a.id as id, a.locator as locator, a.name as name, 
     a.price as price, a.ibutik as ibutik, 'closes' as tableName 
    from  clothes a
  union all
  select b.id,b.locator,b.name,b.price,b.ibutik,'items' from items b 
) foo
where ibutik=0;

使用sqlFiddle验证。