I have this piece of code here and i have the ambiguous error
if (Database.Query(ref reader, "SELECT fromID, toID, status, accountStatus, name FROM friends LEFT JOIN phpbb_users ON ( (user_id = toID) OR (user_id = fromID) ) AND (user_id != " + userID + ") WHERE (fromID=" + userID + " OR toID=" + userID + ")") == false)
{
return null;
}
Any help?
The optimizer is confused on what table accountStatus will it come from since both table contains column name accountStatus. To remove ambiguity error, add a table name before the column name in your SELECT clause.
Either
friends.accountStatus
or
phpbb_users.accountStatus
Specify the table name before column name
table.accountstatus
The ambigous message is probably telling you that your 'accountStatus' column exists in more than one table you are selecting from, so it doesn't know which table to select out of. Prefix the column names in your select list with the table names.
Both tables contains a column with the same name. You should help the parser to identify which table column you want. A simple way is using an alias
"SELECT f.fromID, f.toID, f.status, u.accountStatus, u.name " +
"FROM friends f LEFT JOIN phpbb_users u ON .......
Related
I have thought about using distinct but im not too sure how to do it as a single query for efficiency of code, is there a way? I am basically trying to check if there is already an existing data entry, I am trying to check it with BookingTime. Thanks :)
This is my SQL query:
string bookingInfo = "INSERT INTO Booking(BookingDate, BookingTime, CustomerID, EmployeeID, ServiceType, BookingLength) " +
"VALUES (#BookingDate, #BookingTime, #CustomerID, #EmployeeID, #ServiceType, #BookingLength) " +
"where not exists (SELECT 1 FROM Booking WHERE BookingTime = #BookingTime)";
The error I receive: "Additional information: Query input must contain at least one table or query."
The best way is to let the database do the checking.
Create a unique index or constraint on the table:
create unique index unq_booking_bookingtime on booking(bookingtime);
Note: this is based on your query. It seems unlikely to me that only bookingtime defines uniqueness.
The database will then generate an error if it encounters duplicates. You can prevent the error using insert ignore or insert on duplicate key update (the latter is the preferred method).
The WHERE clause is invalid is invalid in the "INSERT ... VALUES" statement shown.
MySQL does provide an "INSERT ... SELECT ..." form of the INSERT statement (which does not use a VALUES clause). The SELECT statement can have a WHERE clause, but to include a WHERE clause in a SELECT, there has to be a FROM clause. You can use an inline view (aka a derived table) to return a single row, or you could use the builtin Oracle-style dummy table DUAL to return a single row. (We don't care what columns get returned, we just need one row returned.)
For example:
INSERT INTO Booking
( BookingDate
, BookingTime
, CustomerID
, EmployeeID
, ServiceType
, BookingLength
)
SELECT #BookingDate
, #BookingTime
, #CustomerID
, #EmployeeID
, #ServiceType
, #BookingLength
FROM ( SELECT 1 ) i
WHERE NOT EXISTS
( SELECT 1
FROM Booking b
WHERE b.BookingTime = #BookingTime
)
Now the SELECT statement (which can be tested separately from the INSERT) will return either zero or one rows. And whatever row it returns will be passed to the INSERT.
As an alternative to the "NOT EXISTS" predicate, you could use an anti-join pattern:
SELECT #BookingDate
, #BookingTime
, #CustomerID
, #EmployeeID
, #ServiceType
, #BookingLength
FROM ( SELECT 1 ) i
LEFT
JOIN Booking b
ON b.BookingTime = #BookingTime
WHERE b.BookingTime IS NULL
string bookingInfo = "INSERT INTO Booking(BookingDate, BookingTime, CustomerID, EmployeeID, ServiceType, BookingLength) " +
"SELECT #BookingDate, #BookingTime, #CustomerID, #EmployeeID, #ServiceType, #BookingLength " +
" FROM Booking WHERE NOT EXISTS (SELECT * FROM Booking WHERE BookingTime = #BookingTime) LIMIT 1 "
Try this SqlFiddle
I need to select all the columns names only from a SPLANNING_ROOMDATA2 table in such way that those names should not exist in a comma separated list of column names in another table. Here is my query in a C# ASP.NET application. My query generates an error like 'syntax error near Where'.
SqlCommand cmd = new SqlCommand("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Splanning_RoomData2' where COLUMN_NAME NOT IN (SELECT ATTRIBUTENAME FROM SPLANNING_RESTRICTED_ATTRIBUTES)", con);//get only column names
Note, if I remove the second Where clause then I do get a list of columns but that is not what I desire. I have done some searches but none met my needs.
***Edit: As of now, none of the answers are working. I am going to try to change the splanning_restricted_attributes table's to allow one restricted attributed per row--instead of comma separated one. Thanks all. **
You should not store lists as comma separated values. They should be in a separate table, called a junction table with one row per column and table.
Sometimes, though, you are stuck with such a structure. Here is one method for getting what you need:
select c.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS c LEFT JOIN
SPLANNING_RESTRICTED_ATTRIBUTES ra
ON ',' + lower(ra.ATTRIBUTENAME) + ',' LIKE '%,' + lower(c.column_name) + ',%'
where TABLE_NAME = 'Splanning_RoomData2' and ra.ATTRIBUTENAME is null;
Use AND instead of WHERE twice
SqlCommand cmd = new SqlCommand("SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='Splanning_RoomData2'
AND COLUMN_NAME NOT IN (SELECT ATTRIBUTENAME
FROM SPLANNING_RESTRICTED_ATTRIBUTES)", con);
I am just posting the updated answer of #Gordon Linoff answer try the query as,
select c.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS c JOIN
SPLANNING_RESTRICTED_ATTRIBUTES ra
ON ',' + lower(ra.ATTRIBUTENAME) + ',' NOT LIKE '%,' + lower(c.column_name) + ',%'
where c.TABLE_NAME = 'Splanning_RoomData2';
I am working on a project.I have a table tblhomework which have a column students code-which contains students code separated by comma.Now I have few drop downs to search a record among which is search by student name.Now I have students code in my table how should I match it against the student name.I am using the following query,till now I am matching using students code but now I have to match by student name
Query
string studentcode = "%" + txt_studentcode.Text.ToString() + "%";
SELECT
tblhomework.ID,
tblteacher.TEACHERNAME,
tblclass.CLASSNAME,
tblhomework.Title,
tblhomework.HomeworkDetail,
tblhomework.StudentsCode
FROM tblhomework
join tblclass on tblclass.CLASSCODE=tblhomework.ClassCode
join tblteacher on tblteacher.TSHORTNAME=tblhomework.Tshortcode
where tblhomework.StudentsCode like'" + studentcode + "';
Following is the screenshot of the result I am getting
I have a student table which contains student names of students which you can use.
Using FIND_IN_SET in your current SQL:-
SELECT
tblhomework.ID,
tblteacher.TEACHERNAME,
tblclass.CLASSNAME,
tblhomework.Title,
tblhomework.HomeworkDetail,
tblhomework.StudentsCode
FROM tblhomework
JOIN tblclass ON tblclass.CLASSCODE=tblhomework.ClassCode
JOIN tblteacher ON tblteacher.TSHORTNAME=tblhomework.Tshortcode
WHERE FIND_IN_SET('" + studentcode + "', tblhomework.StudentsCode);
However, not this will only work if there are no spaces before / after the commas in the list of student codes
To join that against the student names table (and making assumptions on the layout of that table) use something like this:-
SELECT
tblhomework.ID,
tblteacher.TEACHERNAME,
tblclass.CLASSNAME,
tblhomework.Title,
tblhomework.HomeworkDetail,
tblhomework.StudentsCode ,
tblstudent.StudentsName
FROM tblstudent
JOIN tblhomework ON FIND_IN_SET(tblstudent.StudentsCode, tblhomework.StudentsCode);
JOIN tblclass ON tblclass.CLASSCODE=tblhomework.ClassCode
JOIN tblteacher ON tblteacher.TSHORTNAME=tblhomework.Tshortcode
WHERE tblstudent.StudentsCode = '" + studentcode + "'
Searching by student name (although generally it would be easier if the drop down returned the numeric unique student id):-
SELECT
tblhomework.ID,
tblteacher.TEACHERNAME,
tblclass.CLASSNAME,
tblhomework.Title,
tblhomework.HomeworkDetail,
tblhomework.StudentsCode ,
tblstudent.StudentsName
FROM tblstudent
JOIN tblhomework ON FIND_IN_SET(tblstudent.StudentsCode, tblhomework.StudentsCode);
JOIN tblclass ON tblclass.CLASSCODE=tblhomework.ClassCode
JOIN tblteacher ON tblteacher.TSHORTNAME=tblhomework.Tshortcode
WHERE tblstudent.StudentsName = '" + studentname + "'
You can use 'FIND_IN_SET' function to search in comma separated set of values.
Change your where clause as below:
where FIND_IN_SET( #student_code, tblhomework.studentscode );
Use AddWithValue to bind value of 'studentcode' read from text box.
string studentcode = txt_studentcode.Text.ToString();
myCommand = new MySqlCommand( sql_query_string, connection );
myCommand.Parameters.AddWithValue( "#student_code", studentcode );
And execute.
To store comma separated values in column is bad design you should look at Database Normalization and do normalize your structure by storing all related student codes in a junction table,but as from above comments you said you can't change structure so in mysql you can use FIND_IN_SET() and join your students table ,i am not familiar with c# syntax so i have posted mysql query,also use your original name convention for the columns
SELECT
DISTINCT
h.ID,
t.TEACHERNAME,
c.CLASSNAME,
h.Title,
h.HomeworkDetail,
h.StudentsCode
FROM
tblhomework h
JOIN tblclass c
ON c.CLASSCODE = h.ClassCode
JOIN tblteacher t
ON t.TSHORTNAME = h.Tshortcode
JOIN students s ON(FIND_IN_SET(s.StudentsCode, h.StudentsCode) > 0)
WHERE FIND_IN_SET('studentcode', h.StudentsCode) > 0
OR s.student_name LIKE 'test'
I have got little issue, I'm trying to put another column klisluz.cena to existing query but its giving me errors that: Column klisluz.cena in command SELECT isnt correct, because its not in GROUP BY, but when I insert it in GROUP BY it throws the same error. Where should I put it ?
Thanks in advance. this is the query:
string sQuery = string.Format("SELECT zajsluz.akce,zajsluz.text,klisluz.pocet,klisluz.cena,klisluz.subkey,zajsluz.ID FROM zajsluz LEFT JOIN klisluz ON zajsluz.ID=klisluz.IDzajsluz WHERE zajsluz.akce= '{0}' and ISNULL(klisluz.subkey, '" + vyberradek + "') = '" + vyberradek + "' GROUP BY klisluz.subkey,zajsluz.akce,zajsluz.text,klisluz.pocet,zajsluz.ID", sZakce);
If your column "cena" is a numeric price value, then you could perform an Aggregate Function on it.
You could try to use the MAX(klisluz.cena) to get the maximum value, or SUM(..) to get a sum any other one that could apply to this column type.
http://msdn.microsoft.com/en-us/library/ms173454.aspx
klisluz.cena is not in the group by.
I have joined the same 2 tables twice using different aliases in a SQL query to enable me to select 2 (potentially but not always) different address ids which then link in to the address table.
SELECT C.court_id, C.court_name, CA.court_address, CA2.court_address...
FROM court C " +
JOIN court_addr CA ON C.court_addr_id = CA.court_addr_id " +
JOIN court_addr CA2 ON C.court_postal_addr_id = CA2.court_addr_id " + ...
Now when trying to output the results of this query using ASP.NET C# I'm unsure how to specify which of the two addresses to Response.Write. Putting the alias in front of the column name (as in the 4th string value below) doesn't work and brings up an error. Is there a way of differentiating between the two addresses in C# despite them both having the same column name in the database?
while (myDataReader.Read())
{
string court_id = myDataReader["court_id"].ToString();
string court_name = myDataReader["court_name"].ToString();
string court_address = myDataReader["court_address"].ToString();
string court_postal_address = myDataReader["CA2.court_address"].ToString();
etc.....
Thanking you muchly in advance
You should use an alias in your sql to distinguish them, then you will be able to return the correct value:
SELECT C.court_id,
C.court_name,
CA.court_address as CACourtAddress,
CA2.court_address as CA2CourtAddress
FROM court C " +
JOIN court_addr CA ON C.court_addr_id = CA.court_addr_id " +
JOIN court_addr CA2 ON C.court_postal_addr_id = CA2.court_addr_id " + ...
You should use alias name to distinguish two columns having same name like :
SELECT C.court_id, C.court_name, CA.court_address CourtAddress, CA2.court_address CourtPostalAddress FROM court C
JOIN court_addr CA ON C.court_addr_id = CA.court_addr_id
JOIN court_addr CA2 ON C.court_postal_addr_id = CA2.court_addr_id
And then in C# you can access them very easily :
string court_id = myDataReader["court_id"].ToString();
string court_name = myDataReader["court_name"].ToString();
string court_address = myDataReader["CourtAddress"].ToString();
string court_postal_address = myDataReader["CourtPostalAddress"].ToString();
I hope this helps solve your problem :)
you could access the columns via index if you cannot modify the query.
var foo = MyDataReader[0].ToString();
Or you could modify the query using the AS keyword in your sql statement.
SELECT foo AS bar FROM Baz
In addition to providing a column name alias as bluefeet suggests, another way would be to access the values by index instead of by name in C#.
string theValue = myReader[0] as string ?? String.Empty;
This, however, requires the order of the columns to never change and is thus to be used carefully. Also, this only works as you specifically select the columns by name in the given order in your SQL statement.
This may not work for a SELECT *, as the order of the returned columns is not fixed in a SELECT *.