I have an array of usernames as users:[Test1,Test2].I have to loop through this array and should find the unmatched usernames from table b.I have written the query as below:
def usersArray = []
def find
params.users.each{
find= sql.rows("select distinct name from table a,table b where a.id=b.id and b.name!=:n",[n:it])
if(find.size >0)
{
def usList = ["nm":find]
usersArray.push(usList);
}
}
From the above solution in my result i see both Test 1 and Test 2 even though they match.How should i change the query to display only the unmatched users?
Another way - count the existing rows which match the parameter name, then push those that have zero (forgive the bad syntax):
....
numberFound = sql.rows("select count(*)from table a where a.name=:n",[n:it])
if(numberFound = 0)
{
def usList = ["nm":find]
usersArray.push(usList);
}
...
Here is an example of how you might go about solving this problem. This assumes you have a domain class called User with a property called name which you want to match on.
// given a list of user names
List users = ['Test1', 'Test2', 'Test3', 'Test4']
// find all the users that match those names, and collect the matched names into a List
List matched = User.findAll("from User as u where u.name in (:names)", [names: users]).collect { it.name }
// remove the matched names from the user list and arrive at an 'unmatched' names list
List unmatched = users.minus(matched)
This was written off the top of my head so please forgive any typos or other random assumptions.
UPDATED
Since you seem set on using SQL you might be able to do something like this instead
List users = ['Test1', 'Test2', 'Test3', 'Test4']
List placeholders = []
users.each { placeholders << '?' }
String select = "select distinct name from table a,table b where a.id=b.id and b.name in (${placeholders.join(',')})"
List matched = sql.rows(select, users)
List unmatched = users.minus(matched)
Related
I am trying to query my database with sqlalchemy in python to select all rows except those whose IDs belong to a certain list. Something like this;
exceptList = [1, 3, 5]
db.query.all() except those in exceptList
How do I go about this?
Given this initial setup:
class Question(db.Model):
id = db.Column(db.Integer, primary_key=True)
category = db.Column(db.String)
db.create_all()
# Assign category alternately: id 1 ->, id 2 -> B etc.
db.session.add_all([Question(category='AB'[n % 2]) for n in range(5)])
db.session.commit()
Let's try to get question for category "A", assuming questions 1 - 3 have already been asked.
If you already have the list, you can do
q = Question.query.filter(Question.id.not_in([1, 2, 3]), Question.category == 'A')
next_question = q.one()
print(next_question.id, next_question.category)
If the exception list must be obtained via a query, you can use an EXCEPT clause:
# Create a filter than defines the rows to skip
skip = Question.query.filter(db.or_(Question.id < 4, Question.category == 'B'))
q = Question.query.except_(skip)
next_question = q.one()
print(next_question.id, next_question.category)
This documentation section describes how to use except_ (though it uses UNION as an example).
You can try something like below.
except_list = ["password", "another_column"]
result = session.query(*[c for c in User.__table__.c if c.name not in except_list).all()
Some books have more than one author, I have a table with with book_id and author_id1, author_id2, author_id3, and author_id4. I have a table with author_id and author_name.
How can I join these two tables and the main table with book_id to get the authors names together in a data row from a sql query join.
Example:
SELECT book.book_id, book.title, author.author, book.location
FROM books AS b JOIN book_authors AS ba ON b.book_id = ba.book_id JOIN authors AS a ON REGEX ba.authors_id$ = a.authors_id
Not sure about REGEX ($) use in sql Should display id, title, authors, location
How do I get all authors_id# to match authors_id ( notice one has number at end other does not)?
update: So, I would like to get book_authors.authors_id1 to match authors.authors_id, book_authors.authors_id2 to match authors.authors_id, book_authors.authors_id3 to match authors.authors_id, book_authors.authors_id4 to match authors.authors_id and return all the matching authors in list.
...
# merge book_authors and authors into one dataframe
ba_df.rename(columns= {'authors_id1': 'authors_id'}, inplace=True)
ba_df['authors_id'] = ba_df['authors_id'].map(a_df.set_index('authors_id')['authors_name'])
ba_df.rename(columns = {'authors_id':'authors_name1', 'authors_id2': 'authors_id'}, inplace = True)
ba_df['authors_id'] = ba_df['authors_id'].map(a_df.set_index('authors_id')['authors_name'])
ba_df.rename(columns = {'authors_id':'authors_name2', 'authors_id3': 'authors_id'}, inplace = True)
ba_df['authors_id'] = ba_df['authors_id'].map(a_df.set_index('authors_id')['authors_name'])
ba_df.rename(columns = {'authors_id':'authors_name3', 'authors_id4': 'authors_id'}, inplace = True)
ba_df['authors_id'] = ba_df['authors_id'].map(a_df.set_index('authors_id')['authors_name'])
ba_df.rename(columns = {'authors_id':'authors_name4'}, inplace = True)
...
Was working through another dataframe and got the idea to use map after rename to set_index the same on both dataframes. Now, the map lines can work, just have to rename the common column , so as not to overwrite, in this case it was authors_id, replaced with authors_name1, 2, 3 & 4, which equates to the authors_id1, 2, 3 & 4. And yes, it is not pure sql, but it works for python, which is where I had the problem.
I have two django-models
class ModelA(models.Model):
title = models.CharField(..., db_column='title')
text_a = models.CharField(..., db_column='text_a')
other_column = models.CharField(/*...*/ db_column='other_column_a')
class ModelB(models.Model):
title = models.CharField(..., db_column='title')
text_a = models.CharField(..., db_column='text_b')
other_column = None
Then I want to merge the two querysets of this models using union
ModelA.objects.all().union(ModelB.objects.all())
But in query I see
(SELECT
`model_a`.`title`,
`model_a`.`text_a`,
`model_a`.`other_column`
FROM `model_a`)
UNION
(SELECT
`model_b`.`title`,
`model_b`.`text_b`
FROM `model_b`)
Of course I got the exception The used SELECT statements have a different number of columns.
How to create the aliases and fake columns to use union-query?
You can annotate your last column to make up for column number mismatch.
a = ModelA.objects.values_list('text_a', 'title', 'other_column')
b = ModelB.objects.values_list('text_a', 'title')
.annotate(other_column=Value("Placeholder", CharField()))
# for a list of tuples
a.union(b)
# or if you want list of dict
# (this has to be the values of the base query, in this case a)
a.union(b).values('text_a', 'title', 'other_column')
In SQL query, we can use NULL to define the remaining columns/aliases
(SELECT
`model_a`.`title`,
`model_a`.`text_a`,
`model_a`.`other_column`
FROM `model_a`)
UNION
(SELECT
`model_b`.`title`,
`model_b`.`text_b`,
NULL
FROM `model_b`)
In Django, union operations needs to have same columns, so with values_list you can use those specific columns only like this:
qsa = ModelA.objects.all().values('text_a', 'title')
qsb = ModelB.objects.all().values('text_a', 'title')
qsa.union(qsb)
But there is no way(that I know of) to mimic NULL in union in Django. So there are two ways you can proceed here.
First One, add an extra field in your Model with name other_column. You can put the values empty like this:
other_column = models.CharField(max_length=255, null=True, default=None)
and use the Django queryset union operations as described in here.
Last One, the approach is bit pythonic. Try like this:
a = ModelA.objects.values_list('text_a', 'title', 'other_column')
b = ModelB.objects.values_list('text_a', 'title')
union_list = list()
for i in range(0, len(a)):
if b[i] not in a[i]:
union_list.append(b[i])
union_list.append(a[i])
Hope it helps!!
<?php
select1($conn);
function select2 ($conn,$id ,$name)
{
$stmt = $conn->prepare("SELECT def FROM define WHERE wordkey = ?");
mysqli_stmt_bind_param($stmt, 'i', $id);
$stmt->execute();
$stmt->bind_result($def);
while($stmt->fetch()) {
echo "here"; // for testing
$wordArray += $def;
//I will make a call to the js function here sending id, name and wordArray
}
//$stmt->close();
}
function select1 ($conn){
$stmt2 = $conn->prepare("SELECT id , name FROM words");
$stmt2->execute();
$stmt2->bind_result($id, $name);
while($stmt2->fetch()) {
select2 ($conn,$id ,$name);
}
}
?>
I want to ask question I have words table and def table. in def table i have multiple definitions for the same words.id. Is it possible to select them in one query statement ?
words table have id , name
def table have id, wordkey , definition
I want to retrieve name and for each name select all its definitions so that I will then call a javascript function (id, name, defArray)
to display each name with the array of its definitions.
I thought of doing it through 2 select statement, but the problem is the select2 function is not working.
As I can assume from the very limited details from your question.
Try
select a.name, b.definition from words a, def b where a.id=b.word_id
In the above query we are simply accessing the data from multiple tables.
Please supply some more explanation (possibly with code) for precise bug fixings.
Hope it helps, All the best!
Assuming the following:
words
ID | Word
definitions
ID | WordID | Definition
SELECT D.Definition AS definition, W.Word AS word
FROM definitions D, words W
WHERE W.ID = D.WordID
ORDER BY W.Word ASC
This will display rows of definitions, ordered by the word they correspond to.
I have a table with the following columns...
[Name] = [Transliteration] = [Hexadecimal] = [HexadecimalUTF8]
...with multiple rows of UTF-8 characters, such as:
ङ = ṅa = 0919 = e0a499
ञ = ña = 091e = e0a49e
ण = ṇa = 0923 = e0a4a3
न = na = 0928 = e0a4a8
In order to search for the row that exactly matches ña in the Transliteration column , I enter the following command:
SELECT DISTINCT * FROM Samskrta
WHERE BINARY (Transliteration = concat(0xc3b161))
ORDER BY HexadecimalUTF8;
...which produces 4 rows.
Why is the SQL command not producing only the row that exactly matches ña?
What SQL command produces only the row that exactly matches ña?
The following command produces the same results:
SELECT DISTINCT * FROM Samskrta
WHERE BINARY (Transliteration = 'ña')
ORDER BY HexadecimalUTF8;
FIRST OF ALL, your query can't work as indicated: you are applying BINARY() to the result of the logical comparison, NOT comparing the BINARY() of whatever to whatever.
Try reproducing your code PRECISELY if you expect people to be able to tender assistance.