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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?