我有三张桌子:
members (id, name, surname, usr_img)
user_uploads (imgID, user_id, filename, description, up_time)
img_likes (likeID, img_id, user_id)
我需要从user_uploads获取所有内容,并使用img_id,从成员获取上传者信息并在img_likes表中进行2次计数(检查user_id(来自会话变量)和img_id是否存在并获得img总喜欢)。< / p>
SELECT user_uploads.* AS uu, members.*, COUNT(img_id, user_id) AS usr_liked, COUNT(img_id) AS total_likes
FROM user_uploads
INNER JOIN members AS m ON m.id = uu.user_id -- owner info
INNER JOIN img_likes AS il ON il.img_id = uu.imgID AND il.user_id = ? -- check if logged in user already liked
INNER JOIN img_likes AS ilt ON ilt.img_id = uu.imgID -- total likes
GROUP BY img_id, user_id
ORDER BY up_time DESC
我不需要从img_id中获取任何内容,只需计算行数。我不知道是否需要内连接,可能指定user_id?
并获得计数:
$usr_liked = row['usr_liked'];
$total_likes = rwo['total_likes'];
这会起作用吗?
编辑:添加新查询:
SELECT
user_uploads.*,
(
SELECT *
FROM members m
WHERE m.id = user_uploads.user_id
),
(
SELECT COUNT(*)
FROM img_likes t
WHERE t.img_id = user_uploads.imgID AND t.user_id = ?
) AS user_likes,
(
SELECT COUNT(*)
FROM img_likes t
WHERE t.img_id = user_uploads.imgID
) AS total_likes
FROM user_uploads
ORDER BY up_time DESC
答案 0 :(得分:0)
您可以使用子查询:
SELECT
uu.*,
m.*,
(
SELECT COUNT(t.*)
FROM img_likes t
WHERE t.img_id = uu.imgID AND t.user_id = ?
) AS user_likes,
(
SELECT COUNT(t.*)
FROM img_likes t
WHERE t.img_id = uu.imgID
) AS total_likes
FROM
user_uploads AS uu
INNER JOIN members AS m ON
m.id = uu.user_id
ORDER BY
uu.up_time DESC