How to run a query with multiple condition in mysql? - mysqli

code:
SELECT * FROM `detail` WHERE country='Malaysia' or state='' or region='' ORDER BY rand() LIMIT 4
In this query I want to find record which is related to malaysia. Only one record that I have in my table which is related to country='malaysia' but it show other 4 records. I don't have any idea why its happening?. So, How can I solve this issue? Please help me.
Thank You

You are also including records which have empty string for the state or region. Maybe you should just be checking the country field:
SELECT *
FROM detail
WHERE country = 'Malaysia'
ORDER BY rand()
LIMIT 4;

You can also remove
ORDER BY rand()
because sql doesn't sort the result by default, so this statement is superfluous.

Related

where column in (single value) performance

I am writing dynamic sql code and it would be easier to use a generic where column in (<comma-seperated values>) clause, even when the clause might have 1 term (it will never have 0).
So, does this query:
select * from table where column in (value1)
have any different performance than
select * from table where column=value1
?
All my test result in the same execution plans, but if there is some knowledge/documentation that sets it to stone, it would be helpful.
This might not hold true for each and any RDBMS as well as for each an any query with its specific circumstances.
The engine will translate WHERE id IN(1,2,3) to WHERE id=1 OR id=2 OR id=3.
So your two ways to articulate the predicate will (probably) lead to exactly the same interpretation.
As always: We should not really bother about the way the engine "thinks". This was done pretty well by the developers :-) We tell - through a statement - what we want to get and not how we want to get this.
Some more details here, especially the first part.
I Think this will depend on platform you are using (optimizer of the given SQL engine).
I did a little test using MySQL Server and:
When I query select * from table where id = 1; i get 1 total, Query took 0.0043 seconds
When I query select * from table where id IN (1); i get 1 total, Query took 0.0039 seconds
I know this depends on Server and PC and what.. But The results are very close.
But you have to remember that IN is non-sargable (non search argument able), it will not use the index to resolve the query, = is sargable and support the index..
If you want the best one to use, You should test them in your environment because they both work so good!!

pattern match with SQL

I am still new to writing SQL queries.
I am trying to find all rows that have a specific pattern match that is a combination of a constant_string_1, followed by any combination of integers, followed by another constant_string_2.
So for ex I am trying to find all rows that match:
Roger_117788_Maryland
Roger_188_Maryland
Roger_211_Maryland
I have tried:
select * from cust where cust_string ilike 'Roger_[0-9]_Maryland'
However that query doesn't generates 0 results. I have also tried using [:digit:] and \d but neither has worked. Not sure what I am doing wrong. Any help is appreciated.
Thanks
You can work this with just "%". Ilike may cause issues, so you can use "like" after transforming your column to lower case to match all cases.
select * from cust where lower(cust_string) like 'roger%maryland';
The following worked. I ended up using regexp_instr, but it was the multiple-digit match was where my query was not giving the results.
select * from cust where regexp_instr(cust_string, '^(Roger_)[0-9]{1,10}__Maryland$') > 0'
This did two things. One it achieved the result set above, i.e. Roger_188_Maryland, etc. But it also removed any multiple occurrences of the patterns, so for ex it eliminated a multi-match like Roger_188_Roger_211_Maryland. Thanks everyone for your help.

about sqlite offset - What i do not understand?

If you check SELECT sqlite clause: https://www.sqlite.org/lang_select.html
You will see OFFSET demands EXPR. to get correct result from your database query.
And when I went checking what is EXPR. (Please see this: https://www.sqlite.org/syntax/expr.html) i see theoretically there should be a way to express a function after offset. For an example:
select * from my_table limit 50 offset count(id);
Count function would give you numeric value, however we know this is not possible. So my question is: Is there any way to add functions to offset or am I reading things in wrong way from links?
It is possible to use functions in the LIMIT/OFFSET expressions:
SELECT 42 LIMIT length('x') OFFSET round(0.123);
The count() function does not work here because it is an aggregate function, and inside the OFFSET clause, there is no table or group over which it could be applied.
It does not work in general. You have to select your count(id) in an extra query.
For more help look here:
Sqlite LIMIT / OFFSET query

COUNT(field) returns correct amount of rows but full SELECT query returns zero rows

I have a UDF in my database which basically tries to get a station (e.g. bus/train) based on some input data (geographic/name/type). Inside this function i try to check if there are any rows matching the given values:
SELECT
COUNT(s.id)
INTO
firsttry
FROM
geographic.stations AS s
WHERE
ST_DWithin(s.the_geom,plocation,0.0017)
AND
s.name <-> pname < 0.8
AND
s.type ~ stype;
The firsttry variable now contains the value 1. If i use the following (slightly extended) SELECT statement i get no results:
RETURN query SELECT
s.id, s.name, s.type, s.the_geom,
similarity(
regexp_replace(s.name::text,'(Hauptbahnhof|Hbf)','Hbf'),
regexp_replace(pname::text,'(Hauptbahnhof|Hbf)','Hbf')
)::double precision AS sml,
st_distance(s.the_geom,plocation) As dist from geographic.stations AS s
WHERE ST_DWithin(s.the_geom,plocation,0.0017) and s.name <-> pname < 0.8
AND s.type ~ stype
ORDER BY dist asc,sml desc LIMIT 1;
the parameters are as follows:
stype = '^railway'
pname = 'Amsterdam Science Park'
plocation = ST_GeomFromEWKT('SRID=4326;POINT(4.9492530 52.3531670)')
the tuple i need to be returned is:
id name type geom (displayed as ST_AsText)
909658;"Amsterdam Sciencepark";"railway_station";"POINT(4.9482893 52.352904)"
The same UDF returns quite well for a lot of other stations, but this is one (of more) which just won't work. Any suggestions?
P.S. The use of the <-> operator is coming from the pg_trgm module.
Some ideas on how to troubleshoot this:
Break your troubleshooting into steps. Start with the simplest query possible. No aggregates, just joins and no filters. Then add filters. Then add order by, then add aggregates. Look at exactly where the change occurs.
Try reindexing the database.
One possibility that occurs to me based on this is that it could be a corrupted index used in the second query but not the first. I have seen corrupted indexes in the past and usually they throw errors but at least in theory they should be able to create a problem like this.
If this is correct, your query will suddenly return rows if you remove the ORDER BY clause.
If you have a corrupted index, then you need to pay close attention to hardware. Is the RAM ECC? Is the processor overheating? How are you disks doing?
A second possibility is that there is a typo on a join condition of filter statement. Normally this is something I would suspect first but it is easy enough to weed out index problems to start there. If removing the ORDER BY doesn't change things, then chances are it is a typo. If you can't find a typo, then try reindexing.

iphone sqlite query optimization

I am currently using this sqlite query in my application. Two tables are used in this query.....
UPDATE table1 set visited = (SELECT COUNT(DISTINCT table1.itemId) from 'table2' WHERE table2.itemId = table1.itemId AND table2.sessionId ='eyoge2avao');
It is working correct.... My problem is it is taking around 10 seconds to execute this query and retrieve the result..... Don't know what to do... Almost all other process are in right way.. So it seems the problem is with this query formation...
Plz someone help with how to optimize this query....
Regards,
Brian
Make sure you have indexes on the following (combinations of) fields:
table1.itemId
(This will speed up the DISTINCT clause, since the itemId will already be in the correct order).
table2.itemId, table2.sessionId
This will speed up the WHERE clause of your SELECT statement.
How many rows are there in these tables?
Aso try doing an EXPLAIN on your SELECT command to see if it gives you any helpful advice.