combing two SELECT statements into a JOIN - mysql

I have two tables: table_1: item_id, name ... table_2: image_id, item_id, url
The following function retrieves the 'urls' of the items with the '$name' that is passed in. I first need to get the 'item_id' from table_1 to use in the query. I only need to return the 'url's from table_2.
It currently works fine, but I feel it could be streamlined to be done in one query with a JOIN rather than two separate queries. I've tried using different 'JOIN's to make it work but I can't seem to get it right.
Here's the function as it stands now with the two queries...
function get_items( $name ) {
global $wpdb;
$sql1 = "SELECT `item_id` FROM `table_1` WHERE `name` = '$name'";
$results1 = $wpdb->get_var( $sql1 );
$sql1 = "SELECT `url` FROM `table_2` WHERE `item_id` = '$results1'";
$results2 = $wpdb->get_results( $sql1, ARRAY_A );
return $results2;
}
and here is the 'JOIN' that I tried implementing, but was unsuccessful (I've also switched it around and did a 'LEFT/RIGHT JOIN' as well resulting in the same result) ...
$sql1 = "SELECT `table_2`.`url`
FROM `table_2`
INNER JOIN `table_1`
ON `table_2`.`item_id` = `table_1`.`item_id`
WHERE `table_1`.`item_id` = '$name'";
Any advice on combining these two queries?

The problem with your query is this WHERE table_1.item_id = '$name', it should be the name not the item_id
SELECT b.url
FROM table1 a
INNER JOIN table2 b
ON a.item_id = b.item_id
WHERE a.name = '$name'

select url from table_2 where item_id IN (select item_id from table_1 where name = $name )

Related

Mysql row query to codeigniter query

I have the following Mysql query. Running as needed.
SELECT
t_doc.*, t_user.IDA, t_data.IDA
FROM
( SELECT DISTINCT IDau FROM t_doc ) IDau_list
LEFT OUTER JOIN
(
SELECT
IDd ,IDau
FROM
t_doc
WHERE
doc_type = 'doc'
GROUP BY IDau
)
doc_images ON doc_images.IDau = IDau_list.IDau
LEFT OUTER JOIN
(
SELECT
IDd ,IDau
FROM
t_auto_doc
WHERE
doc_type = 'jpg'
GROUP BY IDau
)
jpg_images ON jpg_images.IDau = IDau_list.IDau
LEFT OUTER JOIN
t_doc ON t_doc.IDdoc = COALESCE(jpg_images.IDd, doc_images.IDd)
LEFT OUTER JOIN
t_user ON t_user.IDau = t_doc.IDau
LEFT OUTER JOIN
t_data ON t_user.IDA = t_data.IDA
But, What I must bring this query to codeigniter Model, in which I have to adapt the query, as example like this...
$this->db->select('u.IDau, a.*');
$this->db->from('t_user u');
$this->db->join('t_doc d', 'd.IDau=u.IDau', 'left');
And ...More.....Here......
But, I got it difficult. Is some one out there might change it Please..
Thanks in advance
As #NEVERMIND Suggest I have accomplish the task using...
$query = $this->db->query("My QUERY WITH A BIT OF CHANGE");
Yes, I should make some change to get the exact Data as i needed.
Thanks for all of your comments and ideas.

How to correlate data from two separate tables

I am a beginner at SQL. I am trying to write the following statement, but where user is in group (so where group_members.user_id = $_SESSION['user_id']).
SELECT `group_name`, `group_description` FROM `groups`
How do I write this sort of query that relates values from two different tables? Sorry if I haven't explained this well.
EDIT: When I use the query provided by Matthew Haugen, I seem to have the following difficulty: only one set of results is returned in an array.
This is my code for the function that does the query:
function group_summary(){
$sql = secure_mysqli("SELECT `group_name`,`group_description` FROM `groups` WHERE `group_id` IN (SELECT `group_id` FROM `group_members` WHERE `user_id` = ?)", array($_SESSION['user_id']), "i");
$groups = $sql;
return $groups;
}
And this is secure_mysqli:
function secure_mysqli($query, $values, $datatypes) {
global $link;
$stmt = mysqli_prepare($link, $query);
if($stmt !== false){
if(is_array($values)){ foreach ($values as &$value) $ref_values[] = &$value;
call_user_func_array("mysqli_stmt_bind_param", array_merge(array($stmt, $datatypes), $ref_values));
mysqli_stmt_execute($stmt);
return #mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
}}}
It sounds like you want either this
SELECT * FROM Groups
WHERE Groups.Id IN (SELECT GroupId FROM Group_Members WHERE User_Id = #userid)
Or this
SELECT * FROM Groups
INNER JOIN Group_Members ON Groups.Id = Group_Members.GroupId
WHERE Group_Members = #userid
You will have to perform what is called a JOIN, it depends on what type you want, see here.
So you can do something like the following
SELECT A.GROUP_NAME
, B.GROUP_DESCRIPTION
FROM TABLE1 A
JOIN TABLE2 B
ON A.UNIQUE_KEY = B.UNIQUE_KEY
WHERE GROUP_MEMBERS.USER_ID = $_SESSION['USER_ID']

how do i get data from array depending on some conditions

I have tables T1 and T2. In T1 I have column cat_id having integer values in array seperated by commma, e.g.
row1=1; row2=1,41; row3=40,1
In T2 I have column id having single integer values, e.g.
row1=1; row2=40; row3=41; row4=0
Now depending on id selected from T2 I want data from T1.
My problem is how do I apply the condition in T1. I am using CodeIgniter. I have tried like this.
$this->db->select('*');
$this->db->where('status', 'yes');
$this->db->where('cat', '1');
$this->db->like('category_id', '1');
$this->db->or_like('category_id', ',1');
$this->db->or_like('category_id', '1,');
$this->db->get('T1')->result_array();
but the problem persists as for id = 1, if there is data in T1 as 51,5 it also get selected.
How do i solve this. thanks in advance
Try using FIND_IN_SET
SELECT
*
FROM T1
LEFT JOIN T2 on FIND_IN_SET(T2.id, T1.cat_id)
WHERE T1.status = 'yes' AND T2.cat = 1
If you think the extra records are coming you can use INNER JOIN instead of LEFT JOIN.
IN COdeigniter
$sql_query = "
SELECT
*
FROM T1
LEFT JOIN T2 on FIND_IN_SET(T2.id, T1.cat_id)
WHERE T1.status = 'yes' AND T2.cat = 1
";
$this->db->query($sql_query);
As to the above question,using in_array() also helps.
$this->db->select('cat_id');
$row = $this->db->get('T1')->result_array();
$list = array();
foreach($row as $ind=>$val){
$c_id = explode(',', $row['cat_id);
if(in_array('1', $c_id){
array_push($list, $val)
}
}

MySQL joins with one to many table relationships

I have no idea if this is possible but is there a way in MySQL to produce a single query where the multiple results of a one to many table join can be set as an array on a key of the result for the one item?
I realise that question isn't very clear so I'll explain what I'm after further:
Firstly, I'm currently using implicit joins and would like to learn more on explicit joins (of which I currently know very little), perhaps these could provide the answer I'm looking for?
For example given two tables:
CREATE TABLE `a` (
`id_a` int(11) NOT NULL AUTO_INCREMENT,
`a_column1` varchar(255) NOT NULL,
...
PRIMARY KEY (`id_a`)
)
CREATE TABLE `b` (
`id_b` int(11) NOT NULL AUTO_INCREMENT,
`id_a` int(11) NOT NULL,
`b_column1` varchar(255) NOT NULL,
...
PRIMARY KEY (`id_b`)
)
Where table b has many entries related to a single entry in table a.
If I were to run the following query:
SELECT a.*, b.* FROM a, b WHERE b.id_a = a.id_a AND a.id_a = x;
I would get an array with multiple entries with the data of the single item id x repeated. What I actually want is a single row returned from table a with a key defined as b which contains an array of the multiple matching entries from table b. I suspect that this is not possible with a query alone, but it would be great if it was. Currently I am doing the following in PHP (where $this->_db is a Zend Framework database adapter). This runs a lot of queries!:
$query = "SELECT * FROM a WHERE id_a = ?";
$items = $this->_db->fetchAll($query, $id);
foreach($items as $key => $item) {
$query = "SELECT * FROM b WHERE id_a = ?";
$items[$key]['b'] = $this->_db->fetchAll($query, $item['id']);
}
Alternatively I can use my original join query and post process, which I suspect is more efficient, but means I need to explicitly copy over the columns I need (a pain and far from elegant):
$query = "SELECT * FROM a, b WHERE a.id_a = b.id_a AND a.id_a = ?";
$items = $this->_db->fetchAll($query, $id);
$output = array('a_column1' => $items[0]['a_column1'], etc...);
$output['b'] = array();
foreach($items as $item) {
$b = array('b_column1' => $item['b_column1'], etc...);
$output['b'][] = $b;
}
Your query that uses implicit JOIN:
SELECT a.*
, b.*
FROM a, b
WHERE b.id_a = a.id_a
AND a.id_a = x
With explicit JOIN:
SELECT a.*
, b.*
FROM a
JOIN b
ON b.id_a = a.id_a
WHERE a.id_a = x
One way to have the data in one query is to use the GROUP_CONCAT() function. But it may not be in a format you can use:
SELECT a.*
, GROUP_CONCAT( b.id_b
ORDER BY b.id_b ASC
SEPARATOR ','
) AS b_ids
, GROUP_CONCAT( b.b_column1
ORDER BY b.id_b ASC
SEPARATOR ','
) AS b_column1s
, ... --- etc
FROM a
JOIN b
ON b.id_a = a.id_a
WHERE a.id_a = x
GROUP BY a.id_a
You're probably looking for an ORM (object-relational mapper), which would handle associations between objects and would be able to return one A object containing an array of B objects.
See Good PHP ORM Library?
Using explicit joins, the query would look like this:
SELECT a.*, b.* FROM a inner join b on b.id_a = a.id_a where a.id_a = x;

join query in same table with condition

I have inserted both category and sub-category in same table.
id , name , mainCat ,
Here is the name of the category .If a user add a subcategory then i will add the parent category to maincat and sub category to the name.
but when come sorting i have sort Category wise.
can any one suggest me best query
As long as you only have two levels of categories then a query like the following using a self-join will suffice. However, if you have many levels (i.e. a hierarchy) then the problem becomes a lot harder. See http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ for more information.
SELECT p.Name, s.Name
FROM Categories s
LEFT JOIN Categories p ON s.mainCat = p.ID
ORDER BY p.Name, s.Name;
i tried with query a lot but finally i made it with php
$category = mysql_query("SELECT * FROM category WHERE mainCat = '' ORDER BY `name` ASC");
while($data = mysql_fetch_array($category)){
$array[] = $data;
$subCategory = mysql_query("SELECT * FROM category WHERE mainCat ='".$data['name']."' ORDER BY `name` ASC");
echo "SELECT * FROM category WHERE mainCat ='".$data['name']."' ORDER BY `name` ASC".'<br/>';
while($data2 = mysql_fetch_array($subCategory)){
if($data2['mainCat']!=""){
$array[] = $data2;
}
}
}
have u try below:
SELECT t1.id, t1.name
FROM tablename t1
LEFT JOIN tableName t2
ON t2.name = t1.mainCat