MySQL收集数据JOIN

时间:2016-05-25 16:56:55

标签: mysql

我目前有这两个表

CREATE TABLE IF NOT EXISTS `players` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `group_id` int(11) NOT NULL DEFAULT '1',
  `account_id` int(11) NOT NULL DEFAULT '0',
  `level` int(11) NOT NULL DEFAULT '1',
  `vocation` int(11) NOT NULL DEFAULT '0',
  ...
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS `player_storage` (
  `player_id` int(11) NOT NULL DEFAULT '0',
  `key` int(10) unsigned NOT NULL DEFAULT '0',
  `value` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`player_id`,`key`),
  FOREIGN KEY (`player_id`) REFERENCES `players`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB;

我想执行以下查询

SELECT
  a.value, 
  b.name,
  b.level, 
  b.vocation
FROM
  player_storage a,
  players b
  LEFT JOIN players_online c AS t
     ON c.player_id = b.id
WHERE
  a.player_id = b.id
  AND a.key = 6723
ORDER BY a.value DESC LIMIT 20

事情是我还想查看表player_online上是否存在记录

CREATE TABLE IF NOT EXISTS `players_online` (
  `player_id` int(11) NOT NULL,
  PRIMARY KEY (`player_id`)
) ENGINE=MEMORY;

但是我的查询似乎有效,但如果player_on存在于players_online

,则无法获取

我只获取字段值,名称,级别,职业但不是与players_online相关的单个字段

1 个答案:

答案 0 :(得分:1)

您应该添加与“在线”表格相关的字段。

例如:

SELECT ...,
IF(c.player_id IS NULL, 'offline', 'online') online
FROM ...

当然,您必须在players_online c As t

中修复双重别名问题

SQLFiddle