我想显示来自三个单独表格的数据,包括图像/符号上的喜欢计数。目前,结果数组只打印一个结果。当我删除计数时,它会打印我想要的所有5个。
$query = " SELECT image_url, image_path, date, location, fname, lname, rating, COUNT(DISTINCT likes.sign_id) as 'count' FROM signs INNER JOIN users ON signs.user_id=users.user_id INNER JOIN likes ON (signs.sign_id=likes.sign_id) WHERE location='Oslo' LIMIT 5"; $result = mysqli_query ( $db_server, $query ) or die ( "Could not find uploads" . mysqli_error ( $db_server ) ); while ( $row = mysqli_fetch_assoc ( $result ) ) { print_r($row);}
我尝试了不同的方法,但问题似乎只与COUNT有关,它确实计算了正确数量的喜欢。因此我不知道为什么它不会输出所有结果。
答案 0 :(得分:2)
您缺少group by
条款:
SELECT
image_url, image_path, date, location, fname, lname, rating,
COUNT(DISTINCT likes.sign_id) as 'count'
FROM
signs
INNER JOIN users ON signs.user_id=users.user_id
INNER JOIN likes ON (signs.sign_id=likes.sign_id)
WHERE location='Oslo'
GROUP BY image_url, image_path, date, location, fname, lname, rating
LIMIT 5;
仅当所有这些列都相同时才会起作用,否则,您需要指定所需的列。
如果您的意思是您希望每行旁边都有一个列,那么您可以使用这样的相关查询:
SELECT
image_url, image_path, date, location, fname, lname, rating,
(SELECT COUNT(DISTINCT l.sign_id) FROM likes l
WHERE signs.sign_id=l.sign_id) as `count`
FROM
signs
INNER JOIN users ON signs.user_id=users.user_id
INNER JOIN likes ON (signs.sign_id=likes.sign_id)
WHERE location='Oslo'
LIMIT 5;