我过去几天一直在尝试完成这个MySQL查询,运气很少。我想将这些多个表及其列组合在一起,然后按照它们共同的顺序排序(不是按名称,而是按内容)。我有以下数据库表:
mb_bans:
mb_ban_records:
mb_kicks:
mb_mutes:
mb_mutes_records:
mb_warnings:
我想要完成的是以下几点:
不幸的是,我更加难以理解如何将这些MySQL表组合在一起,同时又将它们保存在不同的类别中 - 按每个表中的_time列排序。我该如何处理?我尝试检索它们一直都没有成功。我能得到的最接近的是只组合每个列的_time列,然后在查询中给它一个值" date"但是我做不了多少结果。我仍然需要将其称为单独的行,对吗?我可以使用fetchAll,但后来我无法在值中添加任何东西..
$banq = $db->prepare('SELECT banned, banned_by, ban_reason, ban_time, ban_expires_on FROM '.BAN_TABLE.' ORDER BY ban_time DESC');
$kickq = $db->prepare('SELECT kicked, kicked_by, kick_reason, kick_time FROM '.KICK_TABLE.' ORDER BY kick_time DESC');
$muteq = $db->prepare('SELECT muted, muted_by, mute_reason, mute_time, mute_expires_on FROM '.MUTE_TABLE.' ORDER BY mute_time DESC');
$warnq = $db->prepare('SELECT warned, warned_by, warn_reason, warn_time FROM '.WARN_TABLE.' ORDER BY warn_time DESC');
$banq->execute();
$kickq->execute();
$muteq->execute();
$warnq->execute();
基本上我希望将所有这些查询组合为一个+两个_record表。非常感谢任何可以帮助我的建议,因为我花了无数个小时试图自己解决这个问题。
提前致谢!
答案 0 :(得分:3)
试试这个:
SELECT * from (
SELECT banned as Punisher, banned_by as Punished, ban_reason as Reason, ban_expires_on as Expire, ban_time as Date FROM mb_bans
UNION
SELECT kicked as Punisher, kicked_by as Punished, kick_reason as Reason, NULL as Expire, kick_time as Date FROM mb_kicks
UNION
SELECT muted as Punisher, muted_by as Punished, mute_reason as Reason, mute_expires_on as Expire, mute_time as Date FROM mb_mutes
UNION
SELECT warned as Punisher, warned_by as Punished, warn_reason as Reason, NULL as Expire, warn_time as Date FROM mb_warnings
) d order by d.Date DESC;
修改强>
我怎样才能获得记录类型?(IE。返回的结果是来自禁止表,静音表,踢表等)。
SELECT * from (
SELECT banned as Punisher, banned_by as Punished, ban_reason as Reason, ban_expires_on as Expire, 'ban' as TableType, ban_time as Date FROM mb_bans
UNION
SELECT kicked as Punisher, kicked_by as Punished, kick_reason as Reason, NULL as Expire, 'kick' as TableType, kick_time as Date FROM mb_kicks
UNION
SELECT muted as Punisher, muted_by as Punished, mute_reason as Reason, mute_expires_on as Expire, 'mute' as TableType, mute_time as Date FROM mb_mutes
UNION
SELECT warned as Punisher, warned_by as Punished, warn_reason as Reason, NULL as Expire, 'warn' as TableType, warn_time as Date FROM mb_warnings
) d order by d.Date DESC;
答案 1 :(得分:1)
这个问题的通用答案是,
SELECT A.COL, B. COL, C.COL
FROM TABLE1 AS 'A'
INNER JOIN TABLE2 AS 'B' WHERE A.ID = B.ID
INNER JOIN TABLE3 AS 'C' WHERE B.ID = C.ID
.
.
.
<YOU CAN PUT AS MUCH AS JOINS YOU WANT>
ORDER BY <REQUIRED_COL>
现在,在你的巨大场景中这样做。