ZF2 DB Adapter - Column not found: 1054 Unknown column - mysql

I'm using ZF2 DB Adapter and get following error on my query:
Column not found: 1054 Unknown column '"product"'
But "product" is no column, it's a value, so how come?
This is how I build the query:
$select = $this->getGateway()->getSql()->select();
$select->join('keywordlink', 'keywordlink_ref_type = "product" AND keywordlink_ref_id = product_id', ['keyword_count' => new Expression('COUNT(keyword_id)')], Select::JOIN_LEFT);
$select->where(['product_deleted IS NULL']);
$select->group(['product_id']);
Btw, the field keywordlink_ref_id is an ENUM in the mysql database.
When I write the SQL myself it works:
SELECT
product.*, COUNT(DISTINCT keywordlink_keyword_id) AS keyword_count
FROM
adcheck.product
LEFT JOIN
keywordlink
ON
keywordlink_ref_type = "product" AND keywordlink_ref_id = product_id
WHERE
product_deleted IS NULL
GROUP BY
product_id
Thanks

Ok, I don't know why it didn't work as before but it works when I move the
keywordlink_ref_type = "product"
into the where condition:
SELECT
product.*, COUNT(DISTINCT keywordlink_keyword_id) AS keyword_count
FROM
adcheck.product
LEFT JOIN
keywordlink
ON
keywordlink_ref_id = product_id
WHERE
keywordlink_ref_type = "product" AND product_deleted IS NULL
GROUP BY
product_id

$sql = $this->getGateway()->getSql()->select();
$sql->from('product')->join('keywordlink', "keywordlink.ref_id" = "product.id", LEFT);
$sql->where->equalTo( 'keywordlink.column' = 'product.column');
$sql->where->equalTo('product.deleted', NULL);
$sql->group('product.product_id');
The column wasn't found because not pointing table in your query.The solution something like this,but for proper syntax of ZF2 query builder you should also check out this zend2 link: http://framework.zend.com/manual/1.12/en/zend.db.select.html

Related

Unknown column in field list when use raw in Laravel

I have a working mysql query like this:
SELECT mc.cart_id, mc.mystore_user_id, MIN(ci.created_at) AS created_at
FROM dmspro_mys_cart AS mc
INNER JOIN dmspro_mys_cart_item AS ci
ON ci.cart_id = mc.cart_id
WHERE mc.is_noticed = 0 AND ci.created_at < '2019-10-08 07:08:39'
GROUP BY mc.cart_id
And I converted it to query builder in my Laravel project:
public function getMinCreatedAt($cartTime)
{
$oSelect = $this->select("{$this->table}.cart_id", "{$this->table}.mystore_user_id",\DB::raw('MIN(ci.created_at) AS created_at'))
->join('cart_item AS ci', 'ci.cart_id', '=', "{$this->table}.cart_id")
->where("{$this->table}.is_noticed", '=', 0)
->where('ci.created_at', '<', $cartTime)
->groupBy("{$this->table}.cart_id")
->get();
return $oSelect;
}
But when I run this, I got error:
Column not found: 1054 Unknown column 'ci.created_at' in 'field list'
(SQL: select dmspro_mys_cart.cart_id,
dmspro_mys_cart.mystore_user_id, MIN(ci.created_at) AS created_at
from dmspro_mys_cart inner join dmspro_mys_cart_item as
dmspro_mys_ci on dmspro_mys_ci.cart_id =
dmspro_mys_cart.cart_id where dmspro_mys_cart.is_noticed = 0
and dmspro_mys_ci.created_at < 2019-10-09 15:51:37 group by
dmspro_mys_cart.cart_id)
How I can fix this?
Thank you!
UPDATE: dmspro_mys_ is my prefix
Your error message does not align with your query.
In the error message an alias named "dmspro_mys_ci" is mentioned, but it does not exist in your query.
Can you please double check this?
Basically your are debuggen the wrong query.
Update
As laravel is setup with prefixing database tables, the alias "ci" is also prefixed.
When referencing this alias in a DB::raw() the table/alias will not automatically be prefixed, so you have to do that yourself by changing:
\DB::raw('MIN(ci.created_at) AS created_at')
to:
\DB::raw('MIN(dmspro_mys_ci.created_at) AS created_at')

Is there a way to pass an alias column name in a nested sub-query, via WHERE IN statement, to the UPDATE statement?

I came across this -
Using ALIAS column in WHERE recently and I understand why the WHERE clause is giving me an error but I can't seem to figure out any other way to write my nested query. The SELECT sub-query runs completely fine by itself.
The error is as follows:
Error Code: 1054. Unknown column 'actual_start_time' in 'IN/ALL/ANY subquery'
Table Structure:
Students: student_id student_name login_time logout_time
Tests: test_id test_start_time test_end_time
TestStats: test_id student_id test_duration
UPDATE test_stats
SET test_duration = datediff(hour, actual_start_time - actual_end_time)
WHERE (actual_start_time, actual_end_time)
IN (
SELECT
CASE
WHEN (s.login_time > t.test_start_time) THEN s.login_time
ELSE t.test_start_time
END AS actual_start_time,
CASE
WHEN (s.logout_time < t.test_end_time) THEN s.logout_time
ELSE t.test_end_time
END AS actual_end_time
FROM tests AS t, students AS s, test_stats AS ts
WHERE t.test_id = ts.test_id and s.student_id = ts.student_id);
This appears to be what you want:
UPDATE test_stats ts JOIN
tests t
ON t.test_id = ts.test_id JOIN
students s
ON s.student_id = ts.student_id
SET test_duration = timestampdiff(hour,
GREATEST(s.login_time, t.test_start_time),
LEAST(s.logout_time, t.test_end_time)
);

Column not found: execption in laravel

I am working on some maintaince project where all are sql queries but i want to convert it in to laravel. Here is the below query :-
$members = Member::select('members.id','members.first_name',
'members.surname','members.username','members.password',
'members.email','user_access.active',
DB::raw('SUM( IF (user_access.active = "y", 1, 0) ) as acount'))
->join('user_access','user_access.member_id','=','members.id')
->where('special_access','=','n')
->groupby('user_access.member_id')
->having('acount','>','0')
->orderby('members.id','desc')
->orderby('members.username','ASC')
->orderby('user_access.note','DESC')
->paginate(30);
Its giving me error when i execute the query. below the error in having clause
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'acount' in 'having clause' (SQL: select count(*) as aggregate from `members` inner join `user_access` on `user_access`.`member_id` = `members`.`id` where `special_access` = n group by `user_access`.`member_id` having `acount` > 0)
I guess something like this will help you.
$userAccess = DB::table('user_access')
->where('special_access','=','n')
->where('active','y')
->groupby('member_id');
Member::select([
'members.id',
'members.first_name',
'members.surname',
'members.username',
'members.password',
'members.email',
'user_access.active'
])->joinSub($userAccess, 'user_access', function($join){
$join->on('user_access.member_id', '=', 'members.id');
})->orderby('members.id','desc')
->orderby('members.username','ASC')
->orderBy('user_access.note','asc')
->paginate(30);
OR
$members = Member::select([
'members.id',
'members.first_name',
'members.surname',
'members.username',
'members.password',
'members.email',
'user_access.active'
])->join('user_access', function($join){
$join->on('user_access.member_id', '=', 'members.id')->on('user_access.active', '=', DB::raw('"y"'));
})
->where('special_access','=','n')
->groupby('user_access.member_id')
->orderby('members.id','desc')
->orderby('members.username','ASC')
->orderby('user_access.note','DESC')
->paginate(30);
As apokryfos said in the comments:
The paginator will attempt to get the count of the query and will remove all selects from it when doing so leading to this error.
If you just need records with user_access.active = "y" then you do not need to select them in the first place and then try to filter them out by HAVING

Add join to SQL query

I need to add a join 'level' to a pre-existing SQL query... unfortunately I keep getting errors with this query. I'm proabably falling somewhere but I cannot understand how to fix it.
The original query is the following:
SELECT
noleggio.*,
nome AS convenzionato
FROM
anag_convenzionati
RIGHT JOIN (SELECT
noleggio.*, targa, dc_standard AS dcstandard
FROM
veicoli_contratti
RIGHT JOIN (SELECT
noleggio.*,
nome AS assicurazione_pagante
FROM
anag_assicurazioni
RIGHT JOIN (SELECT
fatt_sconto_noleggio,
fatt_prezzo_noleggio,
id AS idnoleggio,
numero,
serie,
id_convenzionato,
stato_noleggio,
modalita_noleggio,
conducente,
locatario,
locazione_in_proprio,
id_assicurazione_pagante,
id_veicolo,
giorni,
fatt_giorni_noleggio,
fatt_prezzo_totale_noleggio,
data_pagamento_cliente_a_convenzionato,
ore_manodopera,
IF(locazione_in_proprio = 1, conducente, locatario) AS cedente
FROM
noleggio_veicoli
WHERE
((data_cancellazione IS NULL) OR (data_cancellazione = ''))
) AS noleggio ON noleggio.id_assicurazione_pagante = anag_assicurazioni.id
) AS noleggio ON noleggio.id_veicolo = veicoli_contratti.id
) AS noleggio ON noleggio.id_convenzionato = anag_convenzionati.id;
I need to join the resulting table with moduli_ocr table in this way:
SELECT
noleggio.*
FROM
(//query//) AS noleggio
LEFT JOIN
moduli_ocr ON moduli_ocr.id_noleggio = noleggio.id;
Where //query// is the code above.
The error I got (running the query in MySQL Workbench is:
Error Code: 1054. Unknown column 'noleggio.id' in 'on clause'
BTW I'm not sure if I have to use RIGHT or LEFT join but I will check this once the query is properly 'running'.
Best regards.
It seems that you assign idnoleggio alias to the field "id". Try joining on
moduli_ocr.id_noleggio = noleggio.idnoleggio;

Django ORM Creates Phantom Alias in SQL Join

I am executing the following code (names changed to protect the innocent, so the model structure might seem weird):
memberships =
models.Membership.objects.filter(
degree__gt=0.0,
group=request.user.get_profile().group
)
exclude_count =
memberships.filter(
member__officerships__profile=request.user.get_profile()
).count()
if exclude_officers_with_profile:
memberships = memberships.exclude(
member__officerships__profile=request.user.get_profile()
)
total_count = memberships.count()
which at this point results in:
OperationalError at /
(1054, "Unknown column 'U1.id' in 'on clause'")
The SQL generated is:
SELECT
COUNT(*)
FROM
`membership`
WHERE (
`membership`.`group_id` = 2 AND
`membership`.`level` > 0.0 AND
NOT (
`membership`.`member_id`
IN (
SELECT
U2.`member_id`
FROM
`membership` U0 INNER JOIN `officers` U2
ON (U1.`id` = U2.`member_id`)
WHERE U2.`profile_id` = 2
)
)
)
It appears that the SQL Join's ON statement is referencing an alias that hasn't been defined. Any ideas why!? I dropped my MySQL database and re-synced the tables from my models to try and ensure that there weren't any inconsistencies there.
The structure of the models I'm using are:
class Membership(models.Model):
member = models.ForeignKey(Member, related_name='memberships')
group = models.ForeignKey(Group, related_name='memberships')
level = models.FloatField(default=0.0)
class Member(models.Model):
name = models.CharField(max_length=32)
class Officer(models.Model):
member = models.ForeignKey(Member, related_name='officerships')
profile = models.ForeignKey(UserProfile)
class UserProfile(models.Model)
group = models.ForeignKey(Group)
class Group(models.Model)
pass
I think this may be a symptom of:
http://code.djangoproject.com/ticket/9188
which was fixed as of django revision 9589, I think. Now how to figure out which revision I'm working from...
Confirmed. When I implemented the change referenced in the ticket above:
http://code.djangoproject.com/changeset/9589
my error went away.