dry69034 2013-08-25 05:06
浏览 65
已采纳

复杂的MySQL查询,多表 - 如何编写此关系查询?

I'm having issues writing this query, it's an odd relation that I can't figure out. I'm wondering if it would be better to just use two mysql queries and merge the results with php?... Anyways.. so here we go.

Here's the tables we're using:

- media -
id 
userId 
accessKey 
internalName 
type
created 
modified

- reposts - 
id
userId
mediaId
created

- users - 
id
username

Basically, what I want to do is get a result set of media items associated with the user who posted it, and then ALSO, in the same result set, include additional rows for media items that have been reposted, and then for reposted media items, instead of associating the media.userId of the media item for the username association, associate the reposts.userId as the username.

Here's a rough idea to illustrate, these two example queries below need to work as 1 to provide a combined result set.

SELECT media.*, users.username,
0 AS reposted
FROM media
LEFT JOIN users ON users.id = media.userId

SELECT media.id, media.accessKey, media.internalName, media.type, media.modified, users.username, reposts.userId, reposts.created,
1 AS reposted
FROM reposts
LEFT JOIN media ON media.id = reposts.mediaId
LEFT JOIN users ON users.id = reposts.userId

How would I go about doing this? Or would I be better off using 2 queries and merging the results with PHP?

  • 写回答

1条回答 默认 最新

  • dsbezji539113152 2013-08-25 07:32
    关注

    You can use UNION in your query, but UNION requires the same number of columns (and same data type if I recall correctly) on both queries:

    (SELECT media.id, media.accessKey, media.internalName, media.type, media.modified, users.username, users.id, media.created,
    0 AS reposted
    FROM media
    LEFT JOIN users ON users.id = media.userId)
    UNION
    (SELECT media.id, media.accessKey, media.internalName, media.type, media.modified, users.username, reposts.userId, reposts.created,
    1 AS reposted
    FROM reposts
    LEFT JOIN media ON media.id = reposts.mediaId
    LEFT JOIN users ON users.id = reposts.userId)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 YOLOv8obb获取边框坐标时报错AttributeError: 'NoneType' object has no attribute 'xywhr'
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸