I have this structure of the tables:
Table Name: collisions
Fields: id, creator1, creator2
(1, 1, 2) - simple data in my sql table
Table Name: creators
Fields: id, artistname
(1, john smith)- simple data in my sql table
(2, steven michael)- simple data in my sql table
What i need is to join these tables so i can get the artist name instead of creator1 id and creator 2 id.
This is what I have done so far:
$this->db->select('collisions.*, creators.artist_name AS cr1, creators.artist_name as cr2');
$this->db->join('creators', 'collisions.creator1 = cr1.id AND collisions.creator2 = cr2.id', 'left');
$data = $this->db->get('collisions')->result();
but I am getting this error:
Unknown column 'cr1.id' in 'on clause'
SELECT `collisions`.*, `creators`.`artist_name` AS cr1, `creators`.`artist_name` as cr2 FROM (`collisions`) LEFT JOIN `creators` ON `collisions`.`creator1` = `cr1`.`id` AND collisions.creator2 = cr2.id
Can someone tell me what I am doing wrong?
This did the job
$this->db->select('collisions.*, cr1.artist_name as cr1, cr2.artist_name as cr2');
$this->db->join('creators AS cr1', 'collisions.creator1 = cr1.id', 'left');
$this->db->join('creators AS cr2', 'collisions.creator2 = cr2.id', 'left');
$data = $this->db->get('collisions')->result();
Please use actual table name instead of alias :
$this->db->select('collisions.*, creators.artist_name AS cr1, creators.artist_name as cr2');
$this->db->join('creators', 'collisions.creator1 = creators.id AND collisions.creator2 = creators.id', 'left');
$data = $this->db->get('collisions')->result();
the reason why you cant use alias is that the execution of sql is in the following order:
1)FROM clause
2)WHERE clause
3)GROUP BY clause
4)HAVING clause
5)SELECT clause
6)ORDER BY clause
since you were using alias which is created in select clause which executes after where clause.
That's why you can not use the alias that which does not exits.
Related
"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');
I can't seem to get this working and it's driving me nuts.
I'm using CodeIgniter's Ignited Datatables library I found on github
I have the below method for getting records from a table joined to another:
public function get_templates_ajax() {
$this->datatables->select('tem.template_id, tem.name, tem.vat, COUNT(itm.template_id) AS total_items');
$this->datatables->from('templates tem');
$this->datatables->join('items itm', 'tem.template_id = itm.template_id', 'left');
$this->datatables->where('tem.user_id', $this->session->user_id);
$this->datatables->group_by('tem.template_id');
$this->datatables->add_column('actions', 'EditDelete', 'tem.template_id, tem.name, tem.vat');
return $this->datatables->generate();
}
Yes, I have a field named user_id in both tables, but I'm not selecting the column, however, I get this error: Duplicate column name 'user_id'.
I specified the columns I want selected as seen below:
$this->datatables->select('tem.template_id, tem.name, tem.vat, COUNT(itm.template_id) AS total_items');
I know if I wanted to select the user_id column, I'd use an alias, but I'm not selecting it.
Doing $this->db->last_query(); dumped this SQL:
SELECT COUNT(*) FROM (SELECT * FROM `templates` `tem` LEFT JOIN `items` `itm` ON `tem`.`template_id` = `itm`.`template_id` WHERE `tem`.`user_id` = '1' GROUP BY `tem`.`template_id`) SqueryAux
So it seems that the select method is being ignored while it is selecting all columns from both tables.
What could I be doing wrong?
After much digging, I solved the problem by making some adjustments to the library.
Apparently, the problem was originating from the get_total_results(); method in the class, more specifically these 2 line:
$subquery = $this->ci->db->get_compiled_select($this->table);
$countingsql = "SELECT COUNT(*) FROM (" . $subquery . ") SqueryAux";
The subquery variable was selecting all columns from the main table and joined tables using dear old *.
Here is what I did to fix the problem:
I replaced the $subquery line with this:
....
//ensure table with alias does not contain more than 1 space between original table name and alias
$this->table = preg_replace('!\s+!', ' ', $this->table);
$tbl = explode(" ", $this->table);
//if table has alias, get it, else get table name
$table = count($tbl) > 1 ? $tbl[1] : $tbl[0];
$subquery = $this->ci->db->get_compiled_select($this->table);
//prefix table/alias to * so it selects columns from the main table only
$subquery = str_replace("*", "{$table}.*", $subquery);
....
Hope it helps someone.
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
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
I'm using CodeIgniter's Active Record Classes and I'm retrieving an error using the following code:
$this->db->select("*");
$this->db->order_by("id");
$this->db->limit($limit, $offset);
$this->db->from("atoms");
$this->db->join("atommeta", "atommeta.atom_id = atoms.atom_id");
$query = $this->db->get();
It produces this error:
Error Number: 1052
Column 'id' in order clause is ambiguous
SELECT * FROM (`atoms`) JOIN `atommeta` ON `atommeta`.`atom_id` = `atoms`.`atom_id` ORDER BY `id` LIMIT 10
Filename: /Applications/MAMP/htdocs/atom/models/atom_model.php
Line Number: 197
Line 197: $query = $this->db->get();
Any ideas as to why? It seems to be something to do with the order_by
The error means that you are trying to order by a column name that is used in more than one table. Update your order_by statement with the name of the table that has the column you want to order by. For example:
$this->db->order_by('atoms.id');
It looks like there is an id column in both your atommeta and atoms tables. Because you are joining these tables you will need to specify what column you want to order by.
You will want
$this->db->order_by("atoms.id");
or
$this->db->order_by("atommeta.id");
You should specify which table that 'id' belogns to.
$this->db->select("*");
$this->db->from("atoms");
$this->db->join("atommeta", "atommeta.atom_id = atoms.atom_id");
pick one:
$this->db->order_by("atommeta.id");
or
$this->db->order_by("atoms.id");