MySQL JOIN查询更多表并在一个选择中返回更多结果

时间:2012-01-11 20:38:30

标签: php mysql innodb

我会问,抱歉我的英语不好:(

我有多个表

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(50) COLLATE utf8_slovak_ci NOT NULL,
  `password` varchar(200) COLLATE utf8_slovak_ci NOT NULL,
  `status` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`,`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_slovak_ci;


CREATE TABLE `user_acl` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_user` int(11) unsigned NOT NULL,
  `group` smallint(5) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_slovak_ci;


CREATE TABLE `user_profil` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(100) COLLATE utf8_slovak_ci NOT NULL,
  `fullname` varchar(100) COLLATE utf8_slovak_ci NOT NULL,
  `profil` text COLLATE utf8_slovak_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_slovak_ci;

查询:

SELECT user.*, prf.*, acl.*
FROM (SELECT * FROM user LIMIT 1) AS user
LEFT JOIN user_acl AS acl ON (acl.id_user = user.id)
INNER JOIN user_profil AS prf ON (user.id = prf.id)

我有表useruser_acluser_profil

表格useruser_profil被编入索引id什么是公共密钥

user_acl在表中有id_user个公用密钥和表user(id),但是user_acluser和我有更多行在一个查询中需要表user_acl中的所有行。

2 个答案:

答案 0 :(得分:1)

您可以让MySQL将多行中的值与GROUP_CONCAT组合成一行:

SELECT user.*, prf.*, GROUP_CONCAT(acl.id), GROUP_CONCAT(acl.group) 
FROM user 
LEFT JOIN user_acl AS acl ON (acl.id_user = user.id) 
INNER JOIN user_profil AS prf ON (user.id = prf.id) 
GROUP BY user.id;

答案 1 :(得分:0)

你做不到。如果需要多个acl行到一个用户行,则必须单独查询。 [编辑]:但是如果您需要使用一个查询,那么您应该使用somekindof按位操作。 http://codingrecipes.com/how-to-write-a-permission-system-using-bits-and-bitwise-operations-in-php