如何在mysql查询

时间:2016-06-15 07:33:53

标签: mysql join

我正在研究mysql加入过程

我有两个用于chat__user和chat_message的表。

chat_user:

   id    name  socketid

   1     raj    123
   2     kumar   1234

chat_message:

  id   chat_from  chat_to  message

   1      123     1235       hello
   2      1235    123        how can i help you? 
   3      123     1235       HOw track my order?

然后,约翰这两个表使用" chat_message.chat_from = chat_user.socketid或chat_message.chat_to = chat_user.socketid "

更改为MyQuery:

    SELECT * FROM `chat_message` INNER JOIN `chat_user` ON chat_message.chat_from = chat_user.socketid OR chat_message.chat_to = chat_user.socketid

结果:

chat_from  chat_to  message                    id   name  socketid 

123        1235     hello                      1    raj    123 
1235        123        how can i help you?     1    raj    123 
123        1235     HOw track my order?        1    raj    123 

我需要将 id 字段值更改为自动增量。

例如:

chat_from  chat_to  message                 id   name  socketid 

  123        1235    hello                   1    raj    123 
  1235       123     how can i help you?     2    raj    123 
  123        1235    How track my order?     3    raj    123 

建议我如何改变这个领域?..

2 个答案:

答案 0 :(得分:1)

您似乎只想添加一个序列号,可以使用变量来完成: -

SELECT sub1.chat_from,
        sub1.chat_to,
        sub1.message,
        @id:=@id + 1 AS id,
        sub1.name,
        sub1.socketid  
FROM
(
    SELECT chat_message.chat_from,
            chat_message.chat_to,
            chat_message.message,
            chat_user.name,
            chat_user.socketid  
    FROM chat_message
    INNER JOIN chat_user 
    ON chat_message.chat_from = chat_user.socketid 
    OR chat_message.chat_to = chat_user.socketid
) sub1
CROSS JOIN
(
    SELECT @id:=0
) sub0

但是,通常您需要在子查询中添加ORDER BY子句以尝试强制序列号所在的顺序。

也不确定是否要在每次聊天对话之间重置序列。

答案 1 :(得分:0)

使用以下查询

SELECT @cust_id := @cust_id+1,c.* 
FROM `chat_message` c,(select @cust_id :=0) r 
INNER JOIN `chat_user` ON c.chat_from = chat_user.socketid 
OR c.chat_to = chat_user.socketid