选择在链接表中具有Count的行

时间:2011-07-14 18:49:40

标签: mysql sql

我怀疑这是一个简单的问题,但我的sql技能并不存在,谷歌也没有帮助我(

)。

我有以下表格(为了便于阅读而被删除):

CREATE TABLE IF NOT EXISTS `PROPERTIES` (
    `ID` int(11) NOT NULL auto_increment,
    PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=111 ;

CREATE TABLE IF NOT EXISTS `PROPERTY_PHOTOS` (
  `ID` int(11) NOT NULL auto_increment,
  `PROPERTY_ID` int(11) NOT NULL,
  `PHOTO` varchar(128) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=911 ;

PROPERTIES.ID = PROPERTY_PHOTOS.PROPERTY_ID

上的哪个链接

我想做的是:

SELECT P.ID FROM PROPERTIES P WHERE COUNT(SELECT PP.ID FROM PROPERTY_PHOTOS PP WHERE PP.PROPERTY_ID = P.ID) > 0

SELECT P.ID FROM PROPERTIES P HAVING COUNT(SELECT PP.ID FROM PROPERTY_PHOTOS PP WHERE PP.PROPERTY_ID = P.ID) > 0

但是,这两个查询在语法上都是不正确的。

有人可以建议我如何仅选择PROPERTY_PHOTOS表中具有相应记录的物业的记录吗?

2 个答案:

答案 0 :(得分:2)

    SELECT P.ID,COUNT(*)
      FROM PROPERTIES P
         , PROPERTY_PHOTOS PP
     WHERE PP.PROPERTY_ID = P.ID 
   GROUP BY P.ID
    HAVING COUNT(*) > 0

或者实际上,如果您不关心计数

,那么常规联接应该有效
SELECT DISTINCT P.ID
  FROM PROPERTIES P
     , PROPERTY_PHOTOS PP
 WHERE PP.PROPERTY_ID = P.ID 

答案 1 :(得分:1)

这应该这样做

 SELECT PROPERTIES.ID, COUNT(*) FROM PROPERTIES, PROPERTY_PHOTOS WHERE PROPERTY_PHOTOS.PROPERTY_ID = PROPERTIES.ID GROUP BY PROPERTIES.ID HAVING COUNT(*) > 0