Mysql
 SQL >> Database >  >> RDS >> Mysql

Unire più tabelle univoche di MySQL e ordinare per una colonna

Prova così:

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;

AGGIORNAMENTO

Come faccio a sapere di che tipo è il record? (cioè se il risultato proviene dalla tabella bans, mutes, kicks, ecc.)

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;

Aggiungere una colonna costante in ogni ramo della UNION è il modo standard per etichettare la provenienza dei record. Se le date possono coincidere e vuoi un ordinamento stabile, aggiungi un criterio secondario, per esempio ORDER BY d.Date DESC, d.TableType.