mysql - SELECT FROM .. TO - mysql

Is it possible in MySQL to select rows for a certain range of items?
For example when I want to select all items in where the first letter of the NAME is between the B and T, alphabetically.
I know I can make this is PHP aswell, but it would save me a bit of time if this is possible in MySQL...
Is it possible, and if so, how?
The ideal situation would be something like this:
$sql="SELECT * FROM paths FROM name=name1 TO name=name6"; //which would select name1, 2, 3, 4, 5, 6.

Using BETWEEN will basically get you there, but you need to use one letter past where you want to end. Experiment until you get the result you desire.
SELECT * FROM paths WHERE UPPER(name) BETWEEN 'B' AND 'U';
The idea here is that everything beginning with a 'T' will sort alphabetically before anything beginning with a 'U'. You need to convert it to upper-case via UPPER() so you don't run up against potential collation problems.
So your results could be like:
B,
Bill
Bob
Jane
Tommy
Travis
But Uwe (He's German) would be excluded.

You can use BETWEEN like:
SELECT * FROM paths WHERE name BETWEEN 'B' AND 'U'

Related

Searching database for addresses with certain outcodes

I am trying to find addresses from a MySQL database by outcode, ie the first letters of a UK postcode. The following snippet works fine for two letter outcodes:
select * from addresstable where LEFT (Postcode, 2) in ('CB','PE','IP')
but I need it to work in cases where the outcode may be only one letter, ie:
select * from addresstable where LEFT (Postcode, 2) in ('B','BS','GL')
and the Left statement will of course fail on the single letter case.
How best can I do this search?
Thanks
Martin
I'm not an expert on UK postcodes, but it seems they always start with either one letter or two, followed by at least one digit. If that is true, you could use PATINDEX to find the first number, and then use SUBSTRING to get the first characters up to that first number:
select *
from addresstable
where SUBSTRING(Postcode,1,PATINDEX('%[0-9]%',Postcode)-1) in ('B','BX','GL')
Apparently, PATINDEX isn't built-in with MySQL. There are some functions you can create that simulates the behavior if you want to go that route. Another option, but a bit more clunky, but may work is to just check the second character to see if it is numeric or not. If it is, use the LEFT for one character, otherwise use the LEFT for two characters:
select *
from #addresstable
where (case when concat('',SUBSTRING(Postcode,2,1) * 1) = SUBSTRING(Postcode,2,1) then left(Postcode,1) else left(Postcode,2) end) in ('B','BX','GL')
You could use an OR clause for length 1
select *
from addresstable
where LEFT(Postcode, 2) in ('BS','GL')
OR LEFT(Postcode, 1) = 'B'
or
select *
from addresstable
where LEFT(Postcode, 2) = 'GL'
OR LEFT(Postcode, 1) = 'B'
Use regular expressions. To get postcodes that start with "B", "BS", or "GL":
where Postcode regexp '^(B|BS|GL)'
Of course, this example is a bit silly because postcodes that start with BS also start with B, so this can be simplified to:
where Postcode regexp '^(B|GL)'

MySQL - WHERE x IN ( column)

I tried something out. Here is a simple example in SQL Fiddle: Example
There is a column someNumbers (comma-seperated numbers) and I tried to get all the rows where this column contains a specific number. Problem is, the result only contains rows where someNumbers starts with the specific number.
The query SELECT * FROM myTable where 2 in ( someNumbers ) only returns the row with id 2 and not the row with id 1.
Any suggestions? Thank you all.
You are storing data in the wrong format! You should not be storing multiple values in a single string column. You should not be storing numbers as strings. Instead, you should have a junction table with one row per id and per number.
Sometimes, you just have no choice, because someone else created a really poorly designed database. For these situations, MySQL has the function find_in_set():
SELECT *
FROM myTable
WHERE find_in_set(2, someNumbers ) > 0;
The right solution, however, is to fix the data model.
While Gordon's answer is a good one, here is a way to do this with like
SELECT * FROM myTable where someNumbers like '2,%' or someNumbers like '%,2,%' or someNumbers like '%,2'
The first like checks if your array starts with the number you are looking for (2). The second one checks if 2 is within the array and the last like tests for appearance at the end.
Note that the commas are essential here, because something like '%2%' would also match ...,123,...
EDIT: As suggested by the OP it may happen that only a single value is present in the row. Consequently, the query must check this case by doing ... someNumbers = '2'
I would suggest this query :
SELECT * FROM myTable where someNumbers like '%2%'
It will select every entry where someNumbers contains '2'
Select * from table_name where coloumn_name IN(value,value,value)
you can use it

mySQL find most common starting letter for values

From a mySQL table I would like to determine the most frequent starting letter; for example if the list is:
day
book
cat
dog
apple
The expected result would ultimately allow me to determine that:
'd' is the most frequent starting letter
'd' has a count of 2
Is there a way to do this without running 26 queries, e.g.:
WHERE myWord LIKE 'a%'
WHERE myWord LIKE 'b%'
...
WHERE myWord LIKE 'y%'
WHERE myWord LIKE 'z%'
I found this SO question which makes me think I can do this in 2 steps:
If I'm not mistaken the approach would be to first build a list of all the first letters using the approach from this SO Answer something like this:
SELECT DISTINCT LEFT(word_name, 1) as letter, word_name
FROM word
GROUP BY (letter)
ORDER BY letter
which I expect would look something like:
a
b
c
d
d
... and then query that list. To do this I would store that new list as a temporary table as per this SO question, something like:
CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1)
and query that for Magnitude as per this SO question, something like.
SELECT column, COUNT(*) AS magnitude
FROM table
GROUP BY column
ORDER BY magnitude DESC
LIMIT 1
Is this a sensible approach?
NOTE:
As sometimes happens, in writing this question I think I figured out a way forward, as yet I have no working code. I'll update the question later with code that either works or which needs help.
In the meanwhile I appreciate any feedback, pointers, proposed answers.
Finally, I'm using PHP, PDO, mySQL for this.
TIA
For what it's worth there was an easier way, this is what I ended up with thanks to both who took the time to answer:
$stmt_common2 = $pdo->prepare('SELECT COUNT(*) as occurence,SUBSTRING(word,1,1) as letter
FROM words
GROUP BY SUBSTRING(word,1,1)
ORDER BY occurence DESC, letter ASC
LIMIT 1');
$stmt_common2->execute();
$mostCommon2 = $stmt_common2->fetchAll();
echo "most common letter: " . $mostCommon2[0]['letter'] . " occurs " . $mostCommon2[0]['occurence'] . " times)<br>";
You can achieve by using this simple query
SELECT COUNT(*) as occurence,SUBSTRING(word_name,1,1) as letter
FROM word
GROUP BY SUBSTRING(word_name,1,1)
ORDER BY occurence DESC, letter ASC
LIMIT 1

Find and replace query

I have a table with part numbers. sometimes people put xxx at the end of the part number when they want to include all of the different possible endings (a lot like the wildcard ### in Access). How do I write a query that will give me all of the part numbers and replace anything ending in xxx with ###?
So if my table has:
1234
1235-xxx
1236
How do I write a query that will give me:
1234
1235-###
1236
In Access, you can use the replace function to change some text into some other text: http://office.microsoft.com/en-ca/access-help/replace-function-HA001228898.aspx
Together with a select statement and the iif function to choose the exact rows that need the replacement, it's a fairly simple operation:
select
iif(
part_num like '*-xxx'
, replace(part_num, '-xxx', '-###')
, part_num
)
from my_table

MySQL Select Query - Get only first 10 characters of a value

Ok, so here is the issue.
I have a table with some columns and 'subject' is one of the columns.
I need to get the first 10 letters from the 'subject' field no matter the 'subject' field contains a string with 100 letters.
For example,
Table - tbl.
Columns - id, subject, value.
SQL Query:
SELECT subject FROM tbl WHERE id ='$id';
The result I am getting is, for example
Hello, this is my subject and how are you
I only require the first 10 characters
Hello, thi
I can understand that I can remove the rest of the characters using php substr() but that's not possible in my case. I need to get the excess characters removed by MySQL. How can this be done?
Using the below line
SELECT LEFT(subject , 10) FROM tbl
MySQL Doc.
SELECT SUBSTRING(subject, 1, 10) FROM tbl
Have a look at either Left or Substring if you need to chop it up even more.
Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.