How to fetch distinct values from multiple rows of select query? - sql

I have used query as
string getPlayers = " Select Player1,Player2,Player3,Player4,Player5 from tbl_game where Player1=" + userid + " OR Player2=" + userid + " OR Player3=" + userid + " OR Player4=" + userid + " OR Player5=" + userid + " AND Complete = 'No' ";
It gives result as multiple rows that fulfills the condition.
But I want to store values of distinct Player1,Player2,Player3,Player4,Player5 in variables returned from select query, so that i can use these values for further case.
How can i do this ?
Please help me. I am very confused.
EDITED :
I got the result of select query as -
(1,2,2,4,5)
(2,3,1,4,5)
(4,3,5,1,2)
Where 1,2,3,4,5 are userids(players).
I want store these userids in variables as -
p1=1 , p2=2 , p3=3 ,p4=4, p5=5

string getPlayer1 = (" select var1 from (" Select distinct Player1 as var1 ,Player2,Player3,Player4,Player5 from tbl_game where Player1=" + userid + " OR Player2=" + userid + " OR Player3=" + userid + " OR Player4=" + userid + " OR Player5=" + userid + " AND Complete = 'No' "));
var1 will have a value of player1. Repeat this for all other players. Hope this is what you want.

Related

Dapper query, combining attributes to use with pagination

I have that query that shows all my Boats, but I would just like to show the active boats.
public Pagination<Boats> GetAll(string name , int pageSize, int pageNumber)
{
var cn = Db.Database.Connection;
var sql = #"SELECT * FROM Boats" +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%')" +
"ORDER BY [Name ] " +
"OFFSET " + pageSize * (pageNumber - 1) + " ROWS " +
"FETCH NEXT " + pageSize + " ROWS ONLY " +
" " +
"SELECT COUNT(Id) FROM Boats" +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%')";
var multi = cn.QueryMultiple(sql, new { Name = name });
var boats= multi.Read<Boats >();
var total = multi.Read<int>().FirstOrDefault();
var paginationList= new Pagination<Boats>()
{
List = boats,
Count = total
};
return paginationList;
}
I have the active and excluded attributes in the table, so I tried to show only the boats that were active, but with this query, it keeps returning all records from the boat table, like frist one
var sql = #"SELECT * FROM Boats " +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%' AND Active=1 AND Excluded=0)" +
"ORDER BY [Name] " +
"OFFSET " + pageSize * (pageNumber - 1) + " ROWS " +
"FETCH NEXT " + pageSize + " ROWS ONLY " +
" " +
"SELECT COUNT(Id) FROM Boats " +
"WHERE (#Name IS NULL OR Name LIKE #Name + '%' AND Active=1 AND Excluded=0)";
Any Ideas how can I combine the Name attribute with the Active and Excluded attributes?
Remove it from the parenthesis:
"WHERE (#Name IS NULL OR Name LIKE #Name + '%') AND Active=1 AND Excluded=0"

Getting Error: Column does not exist

When adding rows to a table I am getting Error: column does not exist and I am not sure why. I know the table does and it is fairly straight forward. Here is what I have to add and here is what the table looks like. Any help would be great and let me know if you have any questions. Thanks!
Whatever value I have in emailField it is giving me the error that emailfield column does not exist
final String addemployee = "insert into employee values ('" + name_field.getText() + "', '" + usersSuper.getText() + "', '" + true + "' , md5('" + passwordField.getText() + "') , " + emailField.getText() + ");";
Here is the table
CREATE TABLE employee
(
name text NOT NULL,
manageremail text,
isadmin boolean NOT NULL,
userpassword text NOT NULL,
email text NOT NULL,
CONSTRAINT "user_Email" PRIMARY KEY (email)
)
Try
final String addemployee = "insert into employee values ('" + name_field.getText() + "', '" + usersSuper.getText() + "', '" + true + "' , md5('" + passwordField.getText() + "') , '" + emailField.getText() + "');";
You've missed quotes around emailField.getText()? it should be '" + emailField.getText() + "'

SQLiteDatabase select with dynamic number of conditions

I am new to databases, so it might be it is very easy.
I have the following database structure:
Table products
Table filters (could contain something like)
Color blue
Color black
Color red
Size small
Brand X
Table relation (has only product id and filter id)
Lets say I want to obtain all products that are black or red and are small, I wrote the following query:
SELECT products.name FROM products
JOIN pfrelation ON
((pfrelation.filter_id=18) AND (pfrelation.filter_id=11 OR pfrelation.filter_id=13) AND products.id=pfrelation.product_id)
In the the example above 11 and 13 represent black and red, while 18 is the id for small. As you might suspect the above query has no results (the id can not be both 18 and 11/13). How can I write the select in order to dynamically add any combination of filters? How can I rewrite the query in the example above?
Thank you
you can achieve this with Dynamic Query.
I don't much know about PostgreSql, but I know SQL Server, so I am giving a example to do same.
Here is SQLFiddel Demo
Create table Product(pid int,name varchar(10),color varchar(10),brand varchar(10),size varchar(10));
insert into product values(1,'ABC','red','X','small');
create table pfrelation(pid int,fid int,relation varchar(100));
insert into pfrelation values(1,10,'Color=''blue''');
insert into pfrelation values(1,11,'Color=''black''');
insert into pfrelation values(1,13,'Color=''red''');
insert into pfrelation values(1,18,'size=''small''');
insert into pfrelation values(1,20,'brand=''X''');
Declare #sql varchar(200)
select #sql = ((select 'pr.' + relation from pfrelation where fid = 18)
+ ' and (' +
(select 'pr.' + relation from pfrelation where fid = 11)
+ ' or ' +
(select 'pr.' + relation from pfrelation where fid = 13)
+ ') and pr.pid=pf.pid' )
select #sql
print('select * from Product pr,pfrelation pf where '+#sql)
exec('select * from Product pr,pfrelation pf where '+#sql)
I build the query dynamically this way:
public ArrayList<Products> getFilteredOnlinePictures( Hashtable<String, List<String>> filters,..)
{
SQLiteDatabase db = getWritableDatabase();
// create query conditions
StringBuffer filtersQuery = new StringBuffer();
for (String key: Collections.list(filters.keys()))
{
List<String> filtersValues = filters.get(key);
if (filtersQuery.length() > 0)
filtersQuery.append(" INTERSECT ");
filtersQuery.append("SELECT " + TABLE_PFRELATIONS + "." + COLUMN_PRODUCT_ID
+ " FROM " + TABLE_PFRELATIONS + " WHERE " + TABLE_PFRELATIONS + "."
+ COLUMN_FILTER_ID + " IN (");
for (String value: filtersValues)
{
long filterID = getIDForFilter(db, key, value);
filtersQuery.append(filterID);
if (filtersValues.indexOf(value) == (filtersValues.size() - 1))
{
// this is the last value
filtersQuery.append(")");
}
else
{
// there are more values
filtersQuery.append(",");
}
}
}
if (filtersQuery.length() > 0)
{
filtersQuery.append(")");
filtersQuery.insert(0, " WHERE " + TABLE_PRODUCTS + ".id" + " IN (");
}
String sql = "SELECT " + TABLE_PRODUCTS + "." + COLUMN_NAME + " FROM " + TABLE_PRODUCTS + filtersQuery.toString();
Cursor c = db.rawQuery(sql, null); ...
The query given as an example will be:
SELECT products.name FROM products
WHERE products.id IN (
SELECT pfrelation.product_id FROM pfrelation WHERE pfrelation.filter_id IN (18)
INTERSECT
SELECT pfrelation.product_id FROM pfrelation WHERE pfrelation.filter_id IN (11,13)
)
This way I could have any filter with any number of values.

Can these two SQL statements be made into one? Changing multiple indices with two constraints

I have a form that users can use to edit data in my database. The database is structured like this:
If a user wants to edit both a FAVE_COLOR and a FAVE_FOOD, how would I go about doing that in my SQL statement? I can think of this, but is there a way to do this in one statement?
string sql1 = "UPDATE MYTABLE " +
"SET PROP_VALUE = '" + form["color"] + "' " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME = 'FAVE_COLOR'"
string sql2 = "UPDATE MYTABLE " +
"SET PROP_VALUE = '" + form["food"] + "' " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME = 'FAVE_FOOD'"
string sql = "UPDATE MYTABLE " +
"SET PROP_VALUE = CASE " +
"WHEN PROP_NAME = 'FAVE_COLOR' THEN '" + form["color"] + "' " +
"WHEN PROP_NAME = 'FAVE_FOOD' THEN '" + form["food"] + "' " +
"END " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME IN ('FAVE_COLOR', 'FAVE_FOOD')"
But beware of SQL injection! You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
You can use case statements:
UPDATE MYTABLE
SET PROP_VALUE = (
CASE favefood
WHEN PROP_NAME = 'FAVE_FOOD'
THEN 'PIZZA'
CASE favecolor
WHEN PROP_NAME = 'FAVE_COLOR'
THEN 'BLUE'
WHERE ID = #myIdValue
For MS SQL Server you can use an UPDATE FROM which will update two properties at the same time, like this:
CREATE TABLE MYTABLE (
ID INT,
PROP_NAME VARCHAR(20),
PROP_VALUE VARCHAR(20));
go
INSERT INTO MYTABLE VALUES (1, 'A','B')
go
INSERT INTO MYTABLE VALUES (1, 'C', 'D')
go
UPDATE MYTABLE
SET PROP_VALUE = X.PROP_VALUE
FROM MYTABLE MT JOIN (
SELECT 'A' AS PROP_NAME, 'F' AS PROP_VALUE
UNION
SELECT 'C' AS PROP_NAME, 'G' AS PROP_VALUE) AS X ON MT.PROP_NAME = X.PROP_NAME
WHERE ID = 1
For other SQL DB server the solution should be similar if not identical.

SQL UPDATE doesn't work with foreign languages (Arabic)

the UPDATE gives ???? if the updater field was written in Arabic and this is my query:
UPDATE students
SET first_name = 'الاسم' , last_name = 'الاسم الاخير' ,
father_name = 'الاسم الاخير' , mother_name = '',
birth_date = '1/1/1990 12:00:00 AM' , education_level = '' ,
address = '' , notes = ''
WHERE student_id = 33
And here is the result of the update:
student_id first_name last_name mother_name father_name birth_date
33 ????? ????? ?????? ??????????? 1990-01-01
//the answer is great and thank you people, another question is that I am using this UPDATE syntax in my C# program
command.CommandText = "UPDATE students SET " +
"first_name = " + "'" + first_name + "'" + " , last_name = " + "'" + last_name + "'" +
" , father_name = " + "'" + father_name + "'" + " , mother_name = " +
"'" + mother_name + "'" + ", birth_date = " + "'" + birth_date + "'" +
" , education_level = " + "'" + education_level + "'" +
" , address = " + "'" + address + "'" + " , notes = " + "'" + notes + "'" +
" WHERE student_id = " + id ;
//how to use the character N
You have forgotten the N prefix before your string literals which is required so they will be treated as nvarchar rather than varchar
SET first_name = N'الاسم' etc.
without that the text is coerced into whatever characters the code page of your default collation can deal with.
Create the database with this collation Arabic_CI_AS, you won't need to put N before the Arabic characters.