mysql – 如何用IF / case选择内连接字段?
作者:互联网
有点棘手.
我正在清理一些数据,但由于数据的大小,它需要花费很长时间才能完成,因此我需要在升级执行时运行该应用程序.所以,我有一张评论表和一张照片表.每条评论记录都有存储在object_id中的photo_d_id或存储在object_id中的photo_id:
if comment_type = 8 then object_id = photo.photo_p_id
if comment_type = 17 then object_id = photo.photo_id
我需要内部加入查询中的照片表,但需要根据comment_type在照片表中的正确字段上执行内部连接.这是不可能的,但举一个我想做的例子:
select *.comments,*.photos
FROM comments
CASE
when comments.comment_type = 8 then inner join photos on comments.object_id = photo.photo_p_id
when comments.comment_type = 17 then inner join photos on comments.object_id = photo.photo_id
有任何想法吗?
解决方法:
试试这个查询(编辑) –
SELECT c.*,
CASE c.comment_type WHEN 8 THEN p1.photo_p_id WHEN 17 THEN p2.photo_id ELSE NULL END photo_id,
CASE c.comment_type WHEN 8 THEN p1.column1 WHEN 17 THEN p2.column1 ELSE NULL END column1
FROM comments c
LEFT JOIN photos p1
ON c.object_id = p1.photo_p_id
LEFT JOIN photos p2
ON c.object_id = p2.photo_id
还有一个变种 –
SELECT c.*, p.*
FROM comments c
JOIN photos p
ON c.comment_type = 8 AND c.object_id = p.photo_p_id OR c.comment_type = 17 AND c.object_id = p.photo_id
标签:mysql,if-statement,inner-join,case 来源: https://codeday.me/bug/20191009/1877220.html