PHP & MYSQL: How to resolve ambiguous column names in subquery - php

After trying to query the following nested query
SELECT ur.userID, us.fullname
FROM tbl_user_recipe AS ur JOIN tbl_user_settings AS us ON ur.userID = us.userID
WHERE relationship = 'analyzed' AND userID IN
( SELECT ux.userID
FROM tbl_user_recipe AS ux
WHERE ux.relationship = 'collected'
);
I'm getting the following, and idea why?
#1052 - Column 'userID' in IN/ALL/ANY subquery is ambiguous

You need to prefix the alias to the table here:
WHERE relationship = 'analyzed' AND ur.userID IN

Related

Yii2 query give different result with sql query

"Table1":
id
name
1
Ulrich
2
Stern
"Table2":
id
school
tid
1
A
1
2
B
1
I want to join 2 table to get all information. With SQL query like this:
SELECT Table1.id,
name,
school
FROM `Table1`
INNER JOIN `Table2`
ON Table1.id = Table2.tid
It gives me all information as I expect (I mean 2 rows with name 'Ulrich').
But when I do with Yii2 query:
$query = self::find();
$query -> alias('t1')
-> innerJoin(['t2'=>'Table2'], 't1.id=t2.tid')
$result = NULL;
if($total = $query->count()) {
$result = $query
-> select([t1.*, t2.school])
->asArray()
->all()
;
$result[0]['count'] = $total;
}
it only gives me 1 row with name 'Ulirch'.
Can anyone help me with this problem. Thank you very much.
If you use ActiveRecord::find() method to create query you will get instance of yii\db\ActiveQuery. This is query designed to load ActiveRecord models. Because of that if you do any type of join and your result set contains primary key of your main model (The model which find() method was called to create query) the ActiveQuery will remove any rows it considers duplicate.
The duplicates are recognised based on main model primary key so the rows in resultset will be considered duplicate even if the data from joined table are different. That's exactly what happened in your case.
To avoid that you have to use query builder instead of ActiveQuery.
Your query can look for example like this:
$query = (new \yii\db\Query())
->from(['t1' => self::tableName()])
->innerJoin(['t2'=>'Table2'], 't1.id=t2.tid');

How to correctly use WHERE with JOIN in SQL and PHP

So I'm trying to implement a JOIN in my PHP but I don't know how to include the WHERE clause with JOIN in my query.
I'm trying to do:
SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located
FROM SpecialFacts
INNER JOIN Habitat ON SpecialFacts.SpeciesID=Habitat.SpeciesID
WHERE SpeciesID="G. cuvier"
Basically I'm trying to make sure the join happens on the tables where the SpeciesID is G. cuvier but everything I have tried so far doesn't work and the error it is giving me now is "Column SpeciesID in where clause is ambiguous".
Here is my relevant PHP code:
<?php
include 'connect.php';
$result = mysqli_query($connect,"SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located FROM SpecialFacts INNER JOIN Habitat ON SpecialFacts.SpeciesID=Habitat.SpeciesID WHERE SpeciesID='G. cuvier'") or die("fail" . mysqli_error($connect));
$i = 0;
while($row = mysqli_fetch_array($result))
{
echo $row[$i];
$i = $i + 1;
}
Column SpeciesID exists in both tables, so it doesn't know which need to be compared to value given as G. cuvier. As you are writing every column name as table name with dot(.), the same should be in where condition column SpecialFacts.SpeciesID = "G. cuvier".
So query should be like:
SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located
FROM SpecialFacts
INNER JOIN Habitat ON SpecialFacts.SpeciesID=Habitat.SpeciesID
WHERE SpecialFacts.SpeciesID="G. cuvier"
It's not giving you that error because you're using WHERE incorrectly. It's giving you that error because there are multiple tables in your query that have a column with that name, hence the "ambiguous". You just need to disambiguate it by adding the table name to the identifier.
WHERE SpecialFacts.SpeciesID="G. cuvier"
or
WHERE Habitat.SpeciesID="G. cuvier"
Since you're inner joining the tables on that column, either table should work for the WHERE clause. I would suggest using the smaller table for performance reasons, but honestly I'm not 100% certain if it will matter or not. You can do EXPLAIN on each one to see how they compare.
Use below query instead
SELECT SpecialFacts.ConservationStatus, SpecialFacts.Reproduction, SpecialFacts.Length, Habitat.Type, Habitat.located
FROM SpecialFacts INNER JOIN Habitat
ON SpecialFacts.SpeciesID=Habitat.SpeciesID
WHERE SpecialFacts.SpeciesID='G. cuvier'
I have used single quote and used column name with table name.

Can't View result while joining 3 tables

I have some trouble when I Joining 3 tables, I use mysqli procedural. here's my query..
$select = $connection->conn->query('SELECT * FROM master_beli, supplier, karyawan WHERE supplier.id_supplier = master_beli.id_supplier AND karyawan.id_karyawan = master_beli.id_karyawan');
After that I viewing with this code
while($fetchData = $select->fetch_array()){
echo $fetchData['id_karyawan'].'<br>';
}
I don't know where the problem is, because I use this query a few months ago and it's worked, but now isn't work..
Could be your issue is related to the ambiguity of the column name id_karyawan present in two tables try use an explicit alias or a explict column naming eg :
$select = $connection->conn->query('SELECT master_beli.id_karyawan
FROM master_beli
INNER JOIN supplier ON supplier.id_supplier = master_beli.id_supplier
INNER JOIN karyawan ON karyawan.id_karyawan = master_beli.id_karyawan');
and as suggested in the code above you should use explicit join sintax ..for better readibilty
(the use of implict join sintax is not more promoted in sql)
SELECT master_beli.id_supplier,master_beli.id_karyawan
FROM master_beli
join supplier on supplier.id_supplier = master_beli.id_supplier
join karyawan on karyawan.id_karyawan = master_beli.id_karyawan;
it work on mysql

SQL: Column is ambigious

I have the following SQL query, which has a subquery in it:
SELECT * FROM `statics` WHERE `mmsi`=
(SELECT `mmsi` FROM `positions`,`active`
WHERE `active.mmsi` = `positions.position_ID`);
But when I execute it, I get the following error:
1052 - Column 'mmsi' in field list is ambiguous
Please help me on adjusting my query.
Without seeing your table structure, this is a wild guess:
SELECT *
FROM `statics`
WHERE `statics.mmsi` = (SELECT `active.mmsi`
FROM `positions`,`active`
WHERE `active.mmsi` = `positions.position_ID`);
but I don't get why are you doing this with a subquery. This one should yield the same results
SELECT statics.*
FROM `statics`, `positions`
WHERE `statics.mmsi` = `positions.position_ID`;

Codeigniter active record left join issue

I have two tables 'accounts_transactions' and 'accounts_bills_transactions'.
I have to left join these two using active record of codeigniter.But the names of key columns used to join are different.So I am not getting the key column from the left table in the output .What query should I write to get the key column from the left table included in the result.
My code is
$this->db->select('*');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_bills_transactions.transaction_id','left');
$query = $this->db->get();
So, as you see the key columns used to join here are , id from left table and transaction_id from second table.The problem is that I am not getting the id from left table in the result.But I am getting all other columns.I assume the problem is because of difference in column names used to join.ie both the column names are not named 'id' .So how can I get the id from left table included in the result.
You could alias them:
$this->db->select('accounts_transatctions.*, account_transactions.id AS a_id,
accounts_bills_transactions.*,
account_bills_transactions.id AS ab_id');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_transactions.transaction_id','left');
$query = $this->db->get();
The two IDs will now be available as a_id and ab_id (or whatever alias you choose)
Note: I'm not sure if you can alias in AR without avoiding escaping (haven't been using CI for a while). Should you get any error for that reason, just pass false as second parameter of $this->db->select():
$this->db->select('...', false);
you can try this if you confuse of using $this->where or $this->join
$query = $this->db->query("select ......");
return $query;
You problem is so simple. You can use this query
$query = $this->db
->select('at.*')
->select('abt.id as abt_id');
->from('accounts_transactions at');
->join('accounts_bills_transactions abt', 'at.id = abt.transaction_id','left');
->get()
->result();
When same column are used in join it selects only one. You need to give alise to the other column in second table. The best practice is to use a structure like this
accounts_transatctions
--------------------------
accounts_transatctions_id
other_columns
accounts_bills_transactions
---------------------------
accounts_bills_transactions_id
accounts_transatctions_id
other_columns

Categories