我正在尝试计算此查询中的行数,但是它没有按预期工作,这会返回一个额外的行,它应该是12,但它是13。
$numPhotos = mysql_num_rows(mysql_query("
SELECT albums.id
FROM albums, albumData
WHERE
(albumData.id=albums.albumID OR albums.albumID=0)
AND
albums.userID=$id
AND albums.state=0
AND albumData.state=0
"));
当我删除OR语句部分,而不计算albumID = 0的行时,它返回11.只有一行其中albumID为0,但它将其计为2?
$numPhotos = mysql_num_rows(mysql_query("
SELECT albums.id
FROM albums, albumData
WHERE
albumData.id=albums.albumID
AND
albums.userID=$id
AND albums.state=0
AND albumData.state=0
"));
答案 0 :(得分:2)
尝试使用JOIN编写查询:
SELECT albums.id FROM albums
LEFT JOIN albumData
ON albums.albumID=albumData.id
AND albums.state=0
AND albumData.state=0
WHERE albums.userID=$id
或
SELECT albums.id FROM albums
LEFT JOIN albumData
ON albums.albumID=albumData.id
WHERE albums.userID=$id
AND albums.state=0
AND albumData.state=0
这会解决您的麻烦吗?
<强>编辑:强>
试试这个
SELECT DISTINCT albums.id FROM albums
INNER JOIN albumData
ON (albums.albumID = albumData.id OR albums.albumID = 0)
AND albums.state=0
AND albumData.state=0
WHERE albums.userID=$id
答案 1 :(得分:0)
只需用count(*)替换您的查询列,如下所示:
SELECT count(*)
FROM albums, albumData
WHERE
(albumData.id=albums.albumID OR albums.albumID=0)
AND
albums.userID=$id
AND albums.state=0
AND albumData.state=0
此查询将返回一行&amp;列,它将包含查询生成的行数。