我想从3个表 pm_conv ,用户,照片中获取数据但是在加入第3个表照片后我得到多行,我尝试分配在LIMIT 1中获取数据,但不能。
以下是查询
SELECT
pm_conv. *, user.username, user.id, photo.url
FROM
pm_conv
JOIN
user ON CASE
WHEN pm_conv.sender_id ='2869'
THEN pm_conv.recipient_id = user.id
WHEN pm_conv.recipient_id ='2869'
THEN pm_conv.sender_id = user.id
END
JOIN
photo ON CASE
WHEN pm_conv.sender_id ='2869'
THEN pm_conv.recipient_id = photo.user_id
WHEN pm_conv.recipient_id ='2869'
THEN pm_conv.sender_id = photo.user_id
END
WHERE
`sender_id`='2869'
OR `recipient_id` ='2869'
ORDER BY
`last_answer_date` DESC
答案 0 :(得分:1)
尝试使用子查询,用于照片表。可能它应该工作。
SELECT
pm_conv. *,
user.username,
user.id,
IF(pm_conv.sender_id ='2869',
(SELECT photo.user_id FROM photo WHERE pm_conv.recipient_id = photo.user_id LIMIT 1 ) ,
IF (pm_conv.recipient_id ='2869',
(SELECT photo.user_id FROM photo WHERE pm_conv.recipient_id = photo.user_id LIMIT 1 ),
'')) as PHOTO_USER
FROM
pm_conv
JOIN
user ON CASE
WHEN pm_conv.sender_id ='2869'
THEN pm_conv.recipient_id = user.id
WHEN pm_conv.recipient_id ='2869'
THEN pm_conv.sender_id = user.id
END
WHERE
`sender_id`='2869'
OR `recipient_id` ='2869'
ORDER BY
`last_answer_date` DESC
答案 1 :(得分:0)
试试这个
SELECT
pm_conv. *, user.username, user.id, photo.url
FROM
pm_conv
JOIN
user ON CASE
WHEN pm_conv.sender_id ='2869'
THEN pm_conv.recipient_id = user.id
WHEN pm_conv.recipient_id ='2869'
THEN pm_conv.sender_id = user.id
END
JOIN
photo ON CASE
WHEN pm_conv.sender_id ='2869'
THEN pm_conv.recipient_id = photo.user_id
WHEN pm_conv.recipient_id ='2869'
THEN pm_conv.sender_id = photo.user_id
END
WHERE
`sender_id`='2869'
OR `recipient_id` ='2869'
ORDER BY
`last_answer_date` DESC limit 1
修改后的查询: -
SELECT
pm_conv. *, user.username, user.id, photo.url
FROM
pm_conv
JOIN
user ON CASE
WHEN pm_conv.sender_id ='2869'
THEN pm_conv.recipient_id = user.id
WHEN pm_conv.recipient_id ='2869'
THEN pm_conv.sender_id = user.id
END
JOIN ((SELECT `photo`.* FROM `photo` join `pm_conv` as pmc ON CASE
WHEN pmc.sender_id ='2869'
THEN pmc.recipient_id = photo.user_id
WHEN pmc.recipient_id ='2869'
THEN pmc.sender_id = photo.user_id
END limit 1)) as photo
ON CASE
WHEN pm_conv.sender_id ='2869'
THEN pm_conv.recipient_id = photo.user_id
WHEN pm_conv.recipient_id ='2869'
THEN pm_conv.sender_id = photo.user_id
END
WHERE
`sender_id`='2869'
OR `recipient_id` ='2869'
ORDER BY
`last_answer_date` DESC
我认为它会给你想要的输出。