Ambigous column name, cannot get table by group_id - sql-server

I have SQL code to call my table in my Laravel controller like this:
elseif(auth()->user()->group_id){
$media = MediaOrder::memberOf(auth()->user()->group_id)
->join('users','users.nik','=','media_order.created_by')
->select('media_order.*','users.nickname')
->get();
But when I tried it it come up with an ambiguous column error, like this:
LOG.error: SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL
Server][SQL Server]Ambiguous column name 'group_id'. (SQL: select
[media_order].*, [users].[nickname] from [media_order] inner join
[users] on [users].[nik] = [media_order].[created_by] where [group_id]
= 6) {"userId":"101","exception":{"errorInfo":["42000",209,"[Microsoft][ODBC
Driver 11 for SQL Server][SQL Server]Ambiguous column name
'group_id'."]}
Does anyone has an solution to this? For joining between tables is working, but I just don't know how to use where to get the table based on group_id.
Thank you!.

It seems like both the media_order and users tables have a group_id column, so perhaps something like the following will allow you to distiguish between them...
$media = DB::table('media_order')
->join('users','users.nik','=','media_order.created_by')
->select('media_order.*','users.nickname')
->where('media_order.group_id', '=', auth()->user()->group_id)
->get();

Related

Laravel MS SQL DB::RAW Query returns "Invalid column name"

I'm using SQL Server within my Laravel application. I need to group/sum a table for the month/year. My query looks like this:
$positions = BelegPos::select(
DB::raw("YEAR(Datum) as year"),
DB::raw("MONTH(Datum) as month"),
DB::raw("SUM(Menge) as stunden")
)->groupBy("year", "month")
->get();
I'll get the following error message:
SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Invalid column name 'year'.
I don't know what's wrong, as the query the way I build it works fine with MySQL servers.
Thanks for any hint in the right direction.
UPDATE
I researched a bit more and read about somthing that points out, that the Select Statement isn't available in the GROUP BY section and that you have to add the same query there. so my query looks now like this:
$positions = selectlineBelegPos::select(
DB::raw("YEAR(Datum) as the_year"),
DB::raw("MONTH(Datum) as the_month"),
DB::raw("SUM(Menge) as stunden")
)
->groupBy(DB::raw("YEAR(Datum) as the_year"),DB::raw("MONTH(Datum) as the_month"))
->get();
Still not the solution but the error message has changed to this:
SQLSTATE[42000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL
Server]Incorrect syntax near the keyword (SQL: select
YEAR(Datum) as the_year, MONTH(Datum) as the_month, SUM(Menge) as
stunden from [BELEGP]
So I think there is just one small thing wrong but can't figure out what.
Any ideas?
Solution
Just found the the solution:
$positions = selectlineBelegPos::select(
DB::raw("YEAR(Datum) AS year"),
DB::raw("MONTH(Datum) AS month"),
DB::raw("SUM(Menge) AS stunden")
)
->groupBy(DB::raw("YEAR([Datum])"),DB::raw("MONTH([Datum])"))
->get();
Indeed isn't the dynamically value names (year and month) unavailable in the GROUPBY clause, instead you have to call the DB::raw again but now without generating the key words again.
thank you all for the support!

Unwanted square brackets inserted in SQL statement from ORM

I'm trying to make a simple select on my table mapped with sqlalchemy but I can't get it to match the exact table name.
As I noticed, the output of this:
class Users(base):
__tablename__ = "users"
[...]
was
[Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'users'
And I tried to fix the error by explicitly writing the database I'm refering to
class Users(base):
__tablename__ = "[homework-3-cc-database].users"
[...]
giving the output:
[Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near ']'.
I noticed that it inserted some square brackets, unwanted. Here is their SQL statement:
[SQL: SELECT TOP 1 [[homework-3-cc-database].users].user_id AS [[homework-3-cc-database].users_user_id]
FROM [[homework-3-cc-database].users]]
This statement, ran from DataGrip works just fine:
SELECT TOP 1 [homework-3-cc-schema].users.user_id
FROM [homework-3-cc-schema].users
Do you have any suggestions regarding how should I fix this?
I had to specify the schema name in the following way:
__table_args__ = {"schema": "homework-3-cc-schema"}

How to find table and column in DB2 with tbspaceid tableid specified in error message

I get following error message when trying to insert an object in the database:
com.ibm.db2.jcc.am.SqlIntegrityConstraintViolationException:
DB2 SQL Error: SQLCODE=-407, SQLSTATE=23502, SQLERRMC=TBSPACEID=2,
TABLEID=19, COLNO=0, DRIVER=4.15.134
How can I retrieve the table/column name for which the error is thrown?
Apparently at the package level, DB2 only works with the IDs and not the names.
You can find them back using the following query:
SELECT C.TABSCHEMA, C.TABNAME, C.COLNAME
FROM SYSCAT.TABLES AS T,
SYSCAT.COLUMNS AS C
WHERE T.TBSPACEID = 2
AND T.TABLEID = 19
AND C.COLNO = 0
AND C.TABSCHEMA = T.TABSCHEMA
AND C.TABNAME = T.TABNAME

Query error with Ambiguous column name

When executing the following SQL query on Microsoft SQL Server 2008 :
SELECT
[ACCOUNT]
,[Mailto]
,[Site_addr_1]
,[Site_addr_2]
,[Site_addr_3]
,[State_Class]
,[Map_Facet]
,[Key_Map]
,[Neighborhood_Code]
,[Neighborhood_Group]
,[Econ_Area]
,[Yr_Impr]
,[Acreage]
,[Prior_Total_Market_Value]
,[Land_Value]
,[Improvement_Value]
,[Extra_features_Value]
,[Total_Appraised_Value]
,[Total_Building_Area]
,[Econ_Bld_Class]
,[LAND_USE_CODE]
FROM [Pdata].[dbo].[Real_acct]
LEFT JOIN [Pdata].[dbo].[Land]
ON (Real_acct.ACCOUNT = LAND.ACCOUNT)
I get the following error:
Msg 209, Level 16, State 1, Line 1
Ambiguous column name 'ACCOUNT'.
You are doing a join and it seems that both tables have the column ACCOUNT and sql server doesn't know if you want the column ACCOUNT from Real_acct or Land.
Try this:
SELECT
Real_acct.ACCOUNT -- or Land.ACCOUNT
,Mailto
,Site_addr_1
,Site_addr_2
,Site_addr_3
,State_Class
,Map_Facet
,Key_Map
,Neighborhood_Code
,Neighborhood_Group
,Econ_Area
,Yr_Impr
,Acreage
,Prior_Total_Market_Value
,Land_Value
,Improvement_Value
,Extra_features_Value
,Total_Appraised_Value
,Total_Building_Area
,Econ_Bld_Class
,LAND_USE_CODE
FROM [Pdata].[dbo].[Real_acct]
LEFT JOIN [Pdata].[dbo].[Land]
ON (Real_acct.ACCOUNT = LAND.ACCOUNT)
The very first column... the server doesn't know if you want Real_acct.ACCOUNT or LAND.ACCOUNT
#majidarif is completely correct.
The reason is that both tables have a column named "Account".
You need to specify which table you want the value returned from.
Even if they are the same you need to be specific.

Need a query in Sqlalchemy with GROUP BY CASE

All i need is a simple query with GROUP BY CASE like
SELECT
COUNT([Personnel].[PERSONNEL_ID]) AS value,
CASE
WHEN ([Personnel].[T_FIRSTNAME] = 'John') THEN 'John'
ELSE 'somethingelse'
END AS somelabel
FROM [Personnel]
GROUP BY
CASE
WHEN ([Personnel].[T_FIRSTNAME] = 'John') THEN 'John'
ELSE 'somethingelse'
END
in Sqlalchemy my query looks like this:
case_groups = case(
[(HrPersonnel.T_FIRSTNAME=='John', 'John')],
else_='somethingelse'
)
volunteers = session_mssql.query(
func.count(HrPersonnel.S_HR_PERSONNEL_ID).label('value'),
case_groups.label('somelabel'))\
.group_by(case_groups)\
.all()
mssql server executes the query without any problem (engine.connect().execute(text_query))
but Sqlalchemy ORM query gives me an error.
File
"c:\projects\sa_test\eggs\sqlalchemy-0.9.2-py2.7.egg\sqlalchemy\engine\default.py",
line 425, in do_execute cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) ('42000', "[42000]
[Microsoft][ODBC SQL Server Driver][SQL Server] Column
'Personnel.T_FIRSTNAME' is invalid in the select list because it is
not contained in either an aggregate function or the GROUP BY clause.
(8120) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server
Driver][SQL Server]Statement(s) could not be prepared. (8180)")
u'SELECT count([Personnel].[PERSONNEL_ID]) AS value, CASE WHEN
([Personnel].[T_FIRSTNAME] = ?) THEN ? ELSE ? END AS somelabel \nFROM
[Personnel] GROUP BY CASE WHEN ([Personnel].[T_FIRSTNAME] = ?) THEN ?
ELSE ? END' ('John', 'John', 'somethingelse', 'John', 'John',
'somethingelse')
Why 'Personnel.T_FIRSTNAME' is invalid in the select list?
any suggestions are welcome.
Thanks,
I don't have an answer per se (although future readers may want to check this thread on the SQLAlchemy Google Group), but I've had a similar issue recently and found a workaround.
Instead of executing the query directly, convert it into a string and execute that. For example:
session.execute(
str(query.selectable.compile(compile_kwargs={'literal_binds': True}))
).fetchall()

Resources