在MySQL连接查询中添加序列号

时间:2015-09-29 11:04:53

标签: mysql

我看到很多答案将序列号添加到一个简单的表中,但是在这里我想将串行密钥添加到连接查询中。我试过这个查询

SELECT  *,@c:=@c+1 AS serialNumber 
FROM 
(SELECT @c:= 0) AS c,
(
  SELECT a.ai_id,a.ai_images,a.user_id,a.ai_like_count,a.ai_comment_count,a.ai_caption,u.display_name,u.first_name,u.email,a.ai_created 
  FROM album_images AS a 
  LEFT JOIN users AS u 
  ON a.user_id=u.user_id 
  WHERE u.email_validation=1 
  AND u.status=1 
  ORDER BY a.ai_created DESC
) AS t 
WHERE 1 
GROUP BY user_id 
ORDER BY ai_created DESC

但是我没有按照正确的顺序获得号码,而是像这样1,5,8。我希望它像1,2,3,4

3 个答案:

答案 0 :(得分:1)

分配序列号后,您将按ai_created对结果集进行排序,从而导致问题。在内部查询中使用排序。这是一个例子:

SELECT  *,@c:=@c+1 AS serialNumber 
    FROM 
    (SELECT @c:= 0) AS c,
    (
      SELECT a.ai_id,a.ai_images,a.user_id,a.ai_like_count,a.ai_comment_count,a.ai_caption,u.display_name,u.first_name,u.email,a.ai_created 
      FROM album_images AS a 
      LEFT JOIN users AS u 
      ON a.user_id=u.user_id 
      WHERE u.email_validation=1 
      AND u.status=1 
      GROUP BY a.user_id 
      ORDER BY a.ai_created DESC
    ) AS t 

答案 1 :(得分:0)

尝试此查询

 set @c=0;
 SELECT @c:=@c+1 AS serialNumber,tab.* 
 FROM (
 SELECT * FROM
  (
   SELECT     a.ai_id,a.ai_images,a.user_id,a.ai_like_count,a.ai_comment_count,a.ai_caption,u.display_name,u.first_name,u.email,a.ai_created 
   FROM album_images AS a 
   LEFT JOIN users AS u ON a.user_id=u.user_id 
   WHERE u.email_validation=1 AND u.status=1 ORDER BY a.ai_created DESC) AS t GROUP BY user_id ORDER BY ai_created DESC
) AS tab

答案 2 :(得分:0)

可以将序列号(SL)添加到UNION查询中。这是KOHA ILS报告的示例:

enter code here:  SELECT  @c:=@c+1 AS 'SL' , t.* 
FROM 
(SELECT @c:= 0 AS cc) AS c,
(
SELECT biblio.biblionumber AS BiblioNumber,
GROUP_CONCAT(items.barcode  ORDER BY items.barcode SEPARATOR ',\r\n') AS 'Accession #', 
biblio.title AS Title, 
biblio.author AS 'Main Author',  
COUNT(items.barcode) AS Qty, 
SUM(items.price) AS 'Price (Tk.)', 
@bill_number :=items.stocknumber AS 'Bill No.' FROM biblio LEFT JOIN items ON ( biblio.biblionumber = items.biblionumber ) 
WHERE 
items.stocknumber =  <<Bill Number>>
GROUP BY biblio.biblionumber
) AS t UNION 
SELECT '','','','','','<b>Grand Total:</b>', SUM(items.price),'' FROM items WHERE items.stocknumber LIKE @bill_number GROUP BY items.stocknumber UNION SELECT '','','','','','<b>Net Payable Amount:</b>', @grand_total:=SUM(items.price),'' FROM items WHERE items.stocknumber LIKE @bill_number  GROUP BY items.stocknumber UNION SELECT '','','<b>Amount Chargeable:</b>', CONCAT("<b>(In Word)"," Tk. ", number_to_words(@grand_total),"Only </b>"),'', '', '',''  UNION
SELECT '','','<b>Print Date-Time:</b>', CONCAT("<b>",NOW(),"</b>"),'', '', '','';