SQL查询 - 如果table1中的行有值,则返回else

时间:2013-01-07 18:00:06

标签: mysql sql union any

我有一个查询,它返回名为posts的表格中的每一行,我现在已经将照片添加到帖子中,因此当用户上传新照片时,它会在帖子中创建一行,然后显示新的照片已上传。我有这个全部工作,问题是当用户删除照片时,我不希望从帖子返回该行。

这是我到目前为止所得到的,它仍会返回所有行。

SELECT p.* FROM posts p WHERE p.toID='$id' AND p.state='0' AND


(
    (
        p.type = '2' AND
        p.post = ANY (SELECT ph.id FROM photos ph WHERE ph.state='0' AND ph.id=p.post)
    ) 
    OR 
    (
        p.type!='2' //I had to add this because it wasn't returning any other posts types 
                        //if there weren't any of the `type=2`, how could I also fix that?
    )
)

ORDER BY p.id DESC LIMIT 10

因此,为了知道返回post行,需要检查的是ph.state是否等于0,如果它不等于0则表示照片已被删除。< / p>

修改

还有办法迫使p.post成为intval吗?数据库中的列是varchar,因为它通常存储基于文本的帖子

表结构:

CREATE TABLE `photos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userID` int(11) NOT NULL,
  `photo` varchar(255) NOT NULL,
  `description` longtext NOT NULL,
  `albumID` int(11) NOT NULL,
  `state` int(11) NOT NULL,
  `date` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=651 ;

-- --------------------------------------------------------


CREATE TABLE `posts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `toID` int(11) NOT NULL,
  `fromID` int(11) NOT NULL,
  `post` longtext NOT NULL,
  `type` int(11) NOT NULL,
  `state` int(11) NOT NULL,
  `date` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=380 ;

2 个答案:

答案 0 :(得分:0)

你有'0'将其更改为0,不带引号

你有'2'将其更改为2,不带引号

编辑:

使间隔只是那样做

p.type&lt; somenumber和p.type&gt; someothernumver

答案 1 :(得分:0)

试试这个:

SELECT DISTINCT p.* 
FROM posts p 
LEFT JOIN photos ph ON p.post  = ph.id AND ph.state = 0 
WHERE p.toID='$id' AND p.state = 0 AND 
        ((ph.id IS NULL AND p.type = 2) OR p.type != 2) 
ORDER BY p.id DESC 
LIMIT 10;