开发者

MySQL Query not selecting correctly from 2 join tables

Table Structure

CREATE TABLE IF NOT EXISTS `blogs` (
  `id` int(11) NOT NULL auto_increment,
  `title` text collate utf8_bin NOT NULL,
  `content` longtext collate utf8_bin NOT NULL,
  `active` tinyint(4) NOT NULL d开发者_如何学编程efault '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=2768 ;

CREATE TABLE IF NOT EXISTS `pics` (
  `id` int(11) NOT NULL auto_increment,
  `blogid` int(11) NOT NULL default '0',
  `islogo` tinyint(4) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=4132 ;

CREATE TABLE IF NOT EXISTS `vdos` (
  `id` int(11) NOT NULL auto_increment,
  `blogid` int(11) NOT NULL default '0',
  `file` varchar(255) collate utf8_bin NOT NULL,
  `title` varchar(255) collate utf8_bin NOT NULL,
  `description` text collate utf8_bin NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=3759 ;

Query

select distinct b.id from blogs b 
left join pics p ON b.id = p.blogid 
left join vdos v ON b.id = v.blogid 
where p.islogo = '0' and b.`active` = '1'

What I intend to do is to list blog ids that have pictures or videos. What this query is doing is that it only lists blogs that have pictures, and does not list blog ids that have only a video.

Can anyone see what I am doing wrong?


That's because you set the condition that pics.islogo is '0'. It can never be '0' for blogs without pictures. Move the condition to the join:

select distinct b.id from blogs b 
left join pics p ON b.id = p.blogid and p.islogo = '0'
left join vdos v ON b.id = v.blogid
where b.`active` = '1'


The p.islogo is what's causing only blog with pictures. You'll have to do

where p.islogo = '0' and b.`active` = '1' or p.islogo IS NULL

To also match blogs without pictures.

Edit: Sorry initially misread the question. The where clause should probably be changed to

WHERE (p.islogo = "0" AND p.id IS NOT NULL) OR (v.id IS NOT NULL)


select from blogs b 
left join pics p ON b.id = p.blogid 
left join vdos v ON b.id = v.blogid 
where p.islogo = '0' and b.`active` = '1' GROUP BY b.id;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜