Use of SQL Statement - Database Operation

Posted by gawrrell on Sun, 05 Jul 2020 17:37:13 +0200

[select] SQL statement query

join(left/right) two-table join/multi-table join

//Multi-table Joint Survey:
$sql = 'SELECT * FROM news LEFT JOIN (news_type, news_photo)ON (news_photo.n_id=news.n_id AND n_type=news_type.id)'; 
//Joint investigation of two tables:
$sql = 'SELECT * FROM s LEFT JOIN sc ON s.sno=sc.sno'; 

Three Tables Joint Check + Tables (Data Processing)

SELECT
        id,
        user_name,
        mobile_phone,
        point,
        type,
        order_sn,
        create_time,
        end_time
FROM
    (
        (
           SELECT  
                    p.id,
                    u.user_name,
                    u.mobile_phone,
                    p.point,
                    p.type,
                    o.order_sn,
                    p.create_time,
                    p.end_time  
            FROM 
                    ecs_user_points AS p
            LEFT JOIN  
                    ecs_users      AS u  ON  p.user_id=u.user_id   
            LEFT JOIN 
                    ecs_order_info AS o  ON  p.order_id=o.order_id 
        )
        UNION ALL
        (
            SELECT  
                    p.id,
                    u.user_name,
                    u.mobile_phone,
                    p.point,
                    p.type,
                    o.order_sn,
                    p.create_time,
                    '' as end_time 
            FROM 
                    ecs_points_consume AS p
            LEFT JOIN  
                    ecs_users      AS u  ON  p.user_id=u.user_id   
            LEFT JOIN 
                    ecs_order_info AS o  ON  p.order_id=o.order_id 
        )
    ) as b
ORDER BY
      create_time DESC

Sequence number increment i++ for row displayed in select statement

How to reorder database query results
or
Let the select query result have an extra self-increasing pseudo-ordinal column

Need to be handled with sql statements.
For example, the original table data is as follows:

Now you want to do that, renumber the sort

Examples of implementation are as follows:

select (@i:=@i+1) as number,end_time,type from ecs_user_points,(select @i:=0) as it  where ......

Topics: SQL Database