简体   繁体   English

MySQL查询无法从2个联接表中正确选择

[英]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 default '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. 我打算做的是列出包含图片或视频的博客ID。 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. 该查询的作用是仅列出具有图片的博客,而不列出仅具有视频的博客ID。

Can anyone see what I am doing wrong? 谁能看到我在做什么错?

That's because you set the condition that pics.islogo is '0'. 这是因为您将pics.islogo设置为“ 0”的条件。 It can never be '0' for blogs without pictures. 对于没有图片的博客,它永远不能为“ 0”。 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. p.islogo是仅导致带有图片的博客的原因。 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子句可能应该更改为

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM