开发者

Get all items from table while joining with a second table in a single query

开发者 https://www.devze.com 2023-03-30 22:30 出处:网络
I got two tables: CREATE TABLE IF NOT EXISTS `groups2rights` ( `groups2rights_group_id` int(11) NOT NULL default \'0\',

I got two tables:

CREATE TABLE IF NOT EXISTS `groups2rights` (
  `groups2rights_group_id` int(11) NOT NULL default '0',
  `groups2rights_right` int(11) NOT NULL default '0',
  PRIMARY KEY  (`groups2rights_group_id`,`groups2rights_right`),
  KEY `groups2rights_right` (`groups2rights_right`)
) ENGINE=InnoDB DEFAULT C开发者_如何学GoHARSET=utf8;

INSERT INTO `groups2rights` (`groups2rights_group_id`, `groups2rights_right`) VALUES (1, 35);

CREATE TABLE IF NOT EXISTS `rights` (
  `right` int(11) NOT NULL auto_increment,
  `right_name` varchar(255) default NULL,
  `description` text NOT NULL,
  `category` int(11) NOT NULL default '0',
  PRIMARY KEY  (`right`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=36 ;

INSERT INTO `rights` (`right`, `right_name`, `description`, `category`) VALUES
(33, 'admin_right_group_add', '', 100),
(34, 'admin_right_group_edit', '', 0),
(35, 'admin_right_group_delete', '', 0);

ALTER TABLE `groups2rights` ADD CONSTRAINT `groups2rights_ibfk_4` FOREIGN KEY (`groups2rights_right`) REFERENCES `rights` (`right`) ON DELETE CASCADE;

Now I tried to select all available Rights and also get if the group has it assigned, but somehow I'm missing some of the rights. Query:

SELECT r.*,g2r.groups2rights_group_id
FROM rights AS r
LEFT JOIN groups2rights AS g2r ON (g2r.groups2rights_right=r.right)
WHERE g2r.groups2rights_group_id=<<ID>> OR g2r.groups2rights_group_id IS NULL
ORDER BY r.category,r.right_name ASC

Any ideas?

Edit: Updated the Code.

Expected Result be 3 Rows with 2 of them Havin a Null field and one having a value set.


If you do

SELECT r.*,g2r.group_id
FROM rights AS r
LEFT JOIN groups2rights AS g2r ON (g2r.right=r.right)
WHERE g2r.group_id=<<#id>> OR g2r.group_id IS NULL
ORDER BY r.category,r.right_name ASC

You will not gets rows where g2r.group_id <> null and also g2r.group_id <> <<#id>>

If you want to get all rows in rights and some of the rows in groups2rights you should do:

SELECT r.*,g2r.group_id
FROM rights AS r
LEFT JOIN (SELECT * FROM groups2rights WHERE group_id=<<#id>>) AS g2r 
ON (g2r.right=r.right) 
ORDER BY r.category,r.right_name ASC

This should work.


So you want to return all results found in the right table? In this case you should be using a RIGHT JOIN. This will return all results from the right table regardless of it matching the left table.

http://www.w3schools.com/sql/sql_join_right.asp

0

精彩评论

暂无评论...
验证码 换一张
取 消