简体   繁体   English

在 MySQL select 语句中组合 2 个表

[英]combining 2 tables in MySQL select statement

I know I can do joins but its not exactly what I want.我知道我可以加入,但它不完全是我想要的。

I'm making a live chat system that has 2 tables mainly: the main chat table (call it table a), and then a mod table (call this one table b).我正在制作一个主要有 2 个表的实时聊天系统:主聊天表(称为表 a),然后是一个 mod 表(称为一个表 b)。 If a user gets suspended, messages reach over 100 for that channel, or they are over 1 week, the messages get moved from the main chat table to the mod table.如果用户被暂停,该频道的消息超过 100 条,或者超过 1 周,则消息将从主聊天表移至 mod 表。

I store the ID of the chat messages as ID(primary) on the main chat table and as chatID on the mod table.我将聊天消息的 ID 存储为主聊天表上的 ID(primary) 和 mod 表上的 chatID。

What I'm doing is making a separate page for my Mods and I want to be able to combine the two tables into 1 area but I want them to be ordered by their respective tables.我正在做的是为我的 Mod 制作一个单独的页面,我希望能够将这两个表合并到一个区域中,但我希望它们按各自的表排序。

So lets say we had the following:因此,可以说我们有以下内容:

Main table ID's: 1,2,4 Mod table ID: 3主表 ID:1,2,4 模块表 ID:3

I want my results to show up 1,2,3,4 no matter which table the ID is in.无论 ID 在哪个表中,我都希望我的结果显示为 1、2、3、4。

Any help is greatly appreciated!任何帮助是极大的赞赏!

Edit: I got the answer and this is what I used to do so:编辑:我得到了答案,这就是我以前这样做的:

SELECT ab.* FROM 
  ((SELECT ID as table_id FROM a 
    WHERE roomID = 'newUsers' ORDER BY ID ASC) 
UNION ALL 
  (SELECT chatID as table_id FROM b 
    WHERE roomID = 'newUsers' ORDER BY chatID ASC)) ab 
ORDER BY ab.table_id 

Use a UNION in a subselect.在子选择中使用UNION

SELECT ab.* FROM (
  SELECT 1 as table_id, * FROM a
UNION ALL
  SELECT 2 as table_id, * FROM b
) ab
ORDER BY ab.id

If you want the result of table A to appear before table B, change the query to:如果您希望表 A 的结果出现表 B 之前,请将查询更改为:

SELECT ab.* FROM (
  SELECT 1 as table_id, * FROM a
UNION ALL
  SELECT 2 as table_id, * FROM b
) ab
ORDER BY ab.table_id, ab.id

Some background一些背景
UNION ALL will merge two tables resultsets into one resultset. UNION ALL将两个 结果集合并为一个结果集。
UNION will do the same but will eliminate duplicate rows. UNION会做同样的事情,但会消除重复的行。
This takes time and slows things down, so if you know there will be no duplicate records (or you don't care about dups) use UNION ALL .这需要时间并减慢速度,因此如果您知道不会有重复记录(或者您不关心重复记录),请使用UNION ALL

See also: http://dev.mysql.com/doc/refman/5.5/en/union.html另请参阅: http://dev.mysql.com/doc/refman/5.5/en/union.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM