Tuesday 4 September 2018

Mysql How to optimize the SQL query with many conditions

Table station_tbl:

station_name   |  fare_adult |  fare_child |  fare_OKU |  type |    stationid

New City            2.00         1.00         1.00       0            19900
Old Village         2.00         1.00         1.00       0            54900
Old City            5.00         2.50         2.50       1            23100
New Castle          1.00         0.50         0.50       1            22900
Adult                                                    2              0
Child                                                    2              1
OKU                                                      2              2
Single                                                   3              0
Return                                                   3              1

my query: display ticket info
SELECT
    A.ticketid,
    B.station_name AS stationid,
    c.station_name AS destination,
    CONVERT(VARCHAR(5), GETDATE(), 108) AS TIME,
    CONVERT(VARCHAR(12), GETDATE(), 103) AS Date,
    D.station_name AS ticket_type,
    e.station_name AS journey_type,
    amount,
    issuedby
FROM ticketcollections AS A,
    station_tbl AS B,
    station_tbl AS c,
    station_tbl AS D,
    station_tbl AS e
WHERE A.ticketidparent = '" + Request("ParentId") + "'
    AND A.stationid = B.stationid
    AND B.type = 0
    AND A.destination = c.stationid
    AND c.type = 0
    AND A.ticket_type = D.stationid
    AND D.type = 4
    AND A.journey_type = e.stationid
    AND e.type = 3

I have combined all the data in 1 table.
This table just for storing name for station name and also ticket type.
because in table ticketcollections just store code (1, 2, 3, 4). So when I want to print ticket then I will refer to this station_tbl for display naming purpose.
Please help me if this query will make the query too slow.
On my PC it is fast but on user's PC it is slow.
I have refered 2 tables only.

try this:
SELECT
    A.ticketid,
    B.station_name AS stationid,
    B.station_name AS destination,
    CONVERT(VARCHAR(5), GETDATE(), 108) AS TIME,
    CONVERT(VARCHAR(12), GETDATE(), 103) AS Date,
    B.station_name AS ticket_type,
    B.station_name AS journey_type,
    amount,
    issuedby
FROM ticketcollections A
    station_tbl AS B,
WHERE A.ticketidparent = '" + Request("ParentId") + "'
    AND A.stationid = B.stationid
    AND B.type in(0,4,3)

0 comments:

Post a Comment