How to match row data against an array of values - sql

Is there a good way to check for matches in a SQL column, using an array of data, without having to loop as shown? Assume the url array has 100+ links, the below is just an example.
url = ["www.site1.com", "www.site2.com"]
url.each do |url|
match = db.execute("SELECT 1 FROM ListData WHERE Link=? ", url)
if match[0][0] == 1
flag = true
end
end

Use WHERE IN clause like this:
SELECT 1 FROM ListData WHERE Link IN ('www.site1.com','www.site2.com')

Related

Symfony 6 & Doctrine: delete an array of elements without looping

$em = $this->doctrine->getManager();
$contact = $em->getRepository(Contact::class)->findby(array('id'=>[1,2,3]));
$em->remove($contact);
will give me an error
EntityManager#remove() expects parameter 1 to be an entity object,
array given.
All answers I could find advise me to loop through the array and delete every record separately. I refuse to do so because I only want to send one statement to the database, resulting in SQL: delete from table where id in (1,2,3)
I think the easiest way is to use the query builder, instead a loop over the remove function.
$em = $this->doctrine->getManager();
$qb = $em->getRepository(Contact::class)->createQueryBuilder('c');
$affected = $qb->delete()
->where('c.id IN (:ids)')
->getQuery()
->execute(['ids' => [1,2,3]]);

SQL SELECT WHERE meta_keywords = '['']'

I have been having trouble query after '['']' in table. The data is inserted from pandas dataframe with datatype object (if it matters).
I want to get make a view without the empty lists. Have tried to write the empty list different ways '['']' , '["''"]' etc. but i cant get it to work.
ex where meta_keywords <> '['']'
If meta_keywords is a string, you would use:
where meta_keywords <> '['']'
or:
where meta_keywords <> '['''']'
Or perhaps it is hard to tell what those middle characters really are and you can use the length:
where length(meta_keywords) > 4
If it is an array (which I am guessing), then one of these might work:
where cardinality(meta_keywords) > 0
or:
where '' <> meta_keywords[1] and cardinality(meta_keywords) = 1

How to write Azure storage table queries for non-existent columns

We have a storage table where we want to add a new integer column (It is in fact an enum of 3 values converted to int). We want a row to be required when:
It is an older row and the column does not exist
It is a new row and the column exists and does not match a particular value
When I just use a not equal operator on the column the old rows do not get returned. How can this be handled?
Update
Assuming a comparison always returns false for the non-existent column I tried somethinglike below (the value of the property will be always > 0 when it exists), which does not work either:
If the (Prop GreaterThanOrEqual -1) condition returns false I assume the value is null.
If not then, the actual comparison happens.
string propNullCondition = TableQuery.GenerateFilterConditionForInt(
"Prop",
QueryComparisons.GreaterThanOrEqual,
-1);
propNullCondition = $"{TableOperators.Not}({propNullCondition})";
string propNotEqualValueCondition = TableQuery.CombineFilters(
propNullCondition,
TableOperators.Or,
TableQuery.GenerateFilterConditionForInt(
"Prop",
QueryComparisons.NotEqual,
XXXX));
Note: The table rows written so far do not have "Prop" and only new rows will have this column. And expectation is the query should return all old rows and the new ones only when Prop != XXXX.
It seems that your code is correct, maybe there is a minor error there. You can follow my code below, which works fine as per my test:
Note: in the filter, the column name is case-sensitive.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("test1");
string propNullCondition = TableQuery.GenerateFilterConditionForInt(
"prop1", //note the column name shoud be case-sensitive here.
QueryComparisons.GreaterThanOrEqual,
-1);
propNullCondition = $"{TableOperators.Not}({propNullCondition})";
TableQuery<DynamicTableEntity> propNotEqualValueCondition = new TableQuery<DynamicTableEntity>()
.Where(
TableQuery.CombineFilters(
propNullCondition,
TableOperators.Or,
TableQuery.GenerateFilterConditionForInt(
"prop1",//note the column name shoud be case-sensitive here.
QueryComparisons.NotEqual,
2)));
var query = table.ExecuteQuery(propNotEqualValueCondition);
foreach (var q in query)
{
Console.WriteLine(q.PartitionKey);
}
The test result:
Here is my table in azure:

How to use If statement in addCondition, YII

I have some conditions to hand on to my dataprovider. Now, my last condition I want only to take place only when the field "edit" is set to true -> In this case I want to check if the editConfirmed field 'editBevestigd' is set to true. If the 'edit' field is empty I don't want to add this last condition.
$criteria->addCondition('bevestigd = 1');
$criteria->addCondition('IF(edit = 1) editBevestigd = 1');
What is the best way to handle this. Can I do this in YII (problem here is that the record is not known yet). Or how do I write this in SQL (I know this last condition isn't right right now..)?
Thanks in advance!
If i right understand what you want then you should use this condition:
WHERE (edit = 1 AND editBevestigd = 1) OR edit = 0
Thus, the condition becomes:
$criteria->addCondition('(edit = 1 AND editBevestigd = 1) OR edit = 0');
You can try like that
//for php variable set or not
if($edit==1){
$criteria->addCondition('editBevestigd=1');
}
//for column set or not
$criteria->addCondition('edit IS NOT NULL AND editBevestigd=1');

django using .extra() got error `only a single result allowed for a SELECT that is part of an expression`

I'm trying to use .extra() where the query return more than 1 result, like :
'SELECT "books_books"."*" FROM "books_books" WHERE "books_books"."owner_id" = %s' % request.user.id
I got an error : only a single result allowed for a SELECT that is part of an expression
Try it on dev-server using sqlite3. Anybody knows how to fix this? Or my query is wrong?
EDIT:
I'm using django-simple-ratings, my model like this :
class Thread(models.Model):
#
#
ratings = Ratings()
I want to display each Thread's ratings and whether a user already rated it or not. For 2 items, it will hit 6 times, 1 for the actual Thread and 2 for accessing the ratings. The query:
threads = Thread.ratings.order_by_rating().filter(section = section)\
.select_related('creator')\
.prefetch_related('replies')
threads = threads.extra(select = dict(myratings = "SELECT SUM('section_threadrating'.'score') AS 'agg' FROM 'section_threadrating' WHERE 'section_threadrating'.'content_object_id' = 'section_thread'.'id' ",)
Then i can print each Thread's ratings without hitting the db more. For the 2nd query, i add :
#continue from extra
blahblah.extra(select = dict(myratings = '#####code above####',
voter_id = "SELECT 'section_threadrating'.'user_id' FROM 'section_threadrating' WHERE ('section_threadrating'.'content_object_id' = 'section_thread'.'id' AND 'section_threadrating'.'user_id' = '3') "))
Hard-coded the user_id. Then when i use it on template like this :
{% ifequal threads.voter_id user.id %}
#the rest of the code
I got an error : only a single result allowed for a SELECT that is part of an expression
Let me know if it's not clear enough.
The problem is in the query. Generally, when you are writing subqueries, they must return only 1 result. So a subquery like the one voter_id:
select ..., (select sectio_threadrating.user_id from ...) as voter_id from ....
is invalid, because it can return more than one result. If you are sure it will always return one result, you can use the max() or min() aggregation function:
blahblah.extra(select = dict(myratings = '#####code above####',
voter_id = "SELECT max('section_threadrating'.'user_id') FROM 'section_threadrating' WHERE ('section_threadrating'.'content_object_id' = 'section_thread'.'id' AND 'section_threadrating'.'user_id' = '3') "))
This will make the subquery always return 1 result.
Removing that hard-code, what user_id are you expecting to retrieve here? Maybe you just can't reduce to 1 user using only SQL.