I have column in table views: 165,75,44,458,458,42,45
This column contain user_ids who viewed a link.
I want to explode it by comma delimiter and count the ids
I tried this but it only counts all the character.
SQL:
SELECT LENGTH(views) FROM questions WHERE question_id=1;
This is the PHP version that I want to do in SQL
$viewers_ids = "165,75,44,458,458,42,45";
$num_of_views = count(array_filter(explode(",", $viewers_ids)));
You can count the commas:
select 1 + length(views) - length(replace(views, ',', ''))
That said, you should fix your data structure. You should not be storing multiple numeric ids in a string column -- that is just wrong in many ways. You should be using a junction/association table.
Tried the other way around i.e. to replace all characters other than ,
Select
Length(REGEXP_REPLACE
(views,'[^\,]*',''))+1 from
table
My immediate reaction is that your table structure needs to change - I would expect there to be another table that joins question links and user_ids with a "visit_id" perhaps, and use visit_id as a foreign key in the views table.
My second reaction is that this is a perfect problem for a shell utility - maybe sed/,/ /g then wc -w, or a small awk script.
To do it in SQL, I might try to figure out how to count the number of commas, and add one. This answer gives you a function that will get you the number of commas by replacing them with "", then substracting the length from the length of the unmodified field: Count the number of occurrences of a string in a VARCHAR field?
Related
I have a small problem, I have a table like this:
id|name|group|date_created
1|Volvo|1,3|06-04-2020 10:00:00
2|Audi|3|06-04-2020 10:00:00
etc....
Now I wish I could get all the records that have the value 1 inside the group column.
I tried LIKE "%1%", but I don't think it's a good query. Can you address me?
SELECT id FROM cars WHERE group LIKE '%1%'
The problem with your query is that it would wrongly match '1' against a list like '45,12,5' for example.
One method is to add commas on both ends before searching:
where concat(',', `group`, ',') like '%,1,%';
But in MySQL, it is much more convenient to use string function find_in_set(), whose purpose is just what you are looking for, ie search for a value in a comma-separated list:
select id from cars where find_in_set('1', `group`) > 0
Notes:
you should fix your data model, and have a separated table to store relationship between ids and groups, with each tuple on a separate row. Related reading: Is storing a delimited list in a database column really that bad?
group is a reserved word in MySQL, so not a good choice for a column name (you would need to surround it with backticks everytime you use it, which is error-prone)
I have a MySQL column which contains a string of scores separated by a semi-colon eg: "5;21;24;25;26;28;117".
This column was created not by design, but by collecting the values from multiple rows in a table using GROUP_CONCAT and GROUP BY. The original data arrived as a spreadsheet with multiple rows with the ID value.
I can use a select clause with REPLACE function to replace the ; with a +.
SELECT values, REPLACE(values,";","+") AS score FROM [table_name] WHERE 1
values score
5;21;24;25;26;28;117 5+21+24+25+26+28+117
However what I need is the sum of: 5+21+24+25+26+28+117 to get a total of 246.
Is there any way to do this in MySQL without using some other scripting language?
The SELECT clause shows me a string of numbers joined with the + symbol.
Am looking for a way to evaluate that string to give me the result: 246
UPDATE:
As I was framing my question, I did more research and came up with this link which solves my problem:
(https://dba.stackexchange.com/questions/120747/evaluate-a-string-value-as-a-computed-expression-in-an-sql-statement-sthg-like).
Am keeping this question and the link to the answer here in case it could help other people searching for the same.
I realized a few records in my SQL database have an extra whitespace in them, but I'm not sure which ones have this extra whitespace. I'm trying to find which records are the same, but the statement I'm using does not differentiate records if they have an extra space at the end.
Currently I'm using the following SQL statement to check if the records are equivalent:
SELECT * FROM TABLE WHERE NAME='TEST ';
This would return records which have the name 'TEST'. How do I find which records have the name 'TEST '?
If you have a table that has multiple rows of similar data, but with random white spaces and other junk stuff laying around it, and you want to check out how much of each specific odd data you have, you can do a grouping with a count.
SELECT Name
,Last Name
,Count(*)
FROM table
GROUP BY NAME
,LAST NAME
This should display all your results with how many of each next to it.
IE:JOHN SMITH 2
JACK SMITH 1
This can be tricky because of the way that databases handle spaces. If you don't want to deal with different situations (does LIKE behave the same way? can regexp handle this), then you could do:
WHERE CONCAT(NAME, 'x') = 'TEST x';
Do note that the this could affect performance, if the query is able to use an index on NAME.
You can try this
SELECT * FROM TABLE WHERE TRIM(NAME)='TEST';
How do I find which records have the name 'TEST '?
One way is:
select * from mytable
WHERE NAME='TEST ' and length(NAME) = length('TEST ');
I'm working with an existing database that has multiple associated id codes listed in a single field, separated by spaces. For example: "21 1894 774"
I'm trying to run a query in which I pull all records containing certain numbers in this field. For example, if I search for "21", I want to match records containing "21 1894 744", "21 4", "1723 21 192", etc.
The problem is that it's also matching partials of other numbers. A query for LIKE '%21%' is matching "221", "215", "1821", etc.
I've tried various combinations with spaces ('% 21%', '%21 %', etc.) and it was better, but they still matched parts of other numbers. I also can't just do numbers surrounded by spaces because they could be in the initial position.
How can I query this table to get all records having a standalone "21" in a space-separated field? I'm stumped!
Thanks!
Try with this conditions :
SELECT * FROM your_table WHERE the_text_field LIKE '21 %' OR the_text_field LIKE '% 21 %' OR the_text_field LIKE '% 21' OR the_text_field = '21'
MySQL support regular expressions. While it's def better to split up your numbers you can search for a match as so:
select * from your_table where the_text_field regexp '\b21\b';
If you want a simple query, the answer from aurel.g is the only way; but it will do a full scan of the whole database on each query, so performace would be atrocious.
If you have to do this frecuently, better fix the database. Add a new table with just two fields, one for a single number, and a foreign key that points to the original record where you found that number. Then run a single scan of the whole data, creating a record for each number on that text field. Finally, add an compound index on both columns.
after that, querying all the records with a single number would be really fast and precise.
I have a table with "unique" values. The problem is that the program, which adds these values also adds 3 different postfixs to the value (2 characters in the end of the value). As a result, I have three variable with three postfixs. So i need get only unique values from bd - somehow sort it out without the last two characters. Are any ideas?
What Camera_id should you return (first,last,maximum,minimum???) if rows have one "unique" value but different Camera_id's. Try something like this:
select
LEFT(camera_name,LENGTH(camera_name)-2), max(camera_id)
from cameras
where site_id=1
group by LEFT(camera_name,LENGTH(camera_name)-2)
Do you want to retrieve the values with the first letter only?
SELECT DISTINCT SUBSTRING(ColumnName, 1,1) a
FROM tablename
ORDER BY a
can you show sample records? it helps a lot when your asking question.