How can I CONCAT fields from different independent tables in MySQL? - php

I'm getting form data and using it to fetch them individually and then concat. My current query is this:
$design_code = $_POST['design_num'];
$design_code .= ':'.$db->single('SELECT code FROM '. table_brands .' WHERE id=?', [$_POST['brand']]);
$design_code .= ':'.$db->single('SELECT code FROM '. table_types .' WHERE id=?', [$_POST['type']]);
$design_code .= ':'.$db->single('SELECT code FROM '. table_quality .' WHERE id=?', [$_POST['quality']]);
$design_code .= ':'.$db->single('SELECT code FROM '. table_sizes .' WHERE id=?', [$_POST['size']]);
All the POST data are independent and hence cannot be joined. What can be a proper replacement query to merge them in one.
PS: $db->single() basically sends one single field value.

Try this
select (select code FROM table1 where id = 1 ) as code1, (select code FROM table2 where id = 1 ) as code2, table3.code3 FROM table3 where id = 1
The result will get in a single row.
And using UNION query the result will come in more than one row.
EDIT
Update query as per your last comment "Please check: pastebin.com/qGmp8ZKq"
select (select code FROM brand where id = 2 ) as code1, type.code FROM type where id = 6

Related

How can I order the results of an SQL query by the count of another table based on a shard ID?

I have an SQL query that fetches posts from a database. Everything works fine, but now I need to order the results by the number of comments each post has. The comments are on a separate table and they have a post_id column that links it to the post. I need to order the posts by the count of the comments table based on a shard ID? I have tried everything but every time I try to add something to my query it stops running completely and leaves my page blank. I need help to know where to put the other JOIN statement. This is my query:
$union = "UNION ALL
(
SELECT DISTINCT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
LEFT JOIN walllikes_track
ON wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id."
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) ";
The comments table is called wallcomments and it has a column called post_id. I know I need to use JOIN and COUNT but I don't know where to put it within my current code.
Try this query, I didn't run but i updated it.
SELECT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) " AND wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id.";
A more readable query might look like this...
At least then we'd have a chance.
SELECT DISTINCT p.p_id
, p.is_profile_notes
, p.times_viewed
, p.columnTimesShared
, p.marked
, p.secure_id
, p.media...
FROM wallposts p...

how to combine more than one mysql query into single query

i have 3 different queries like below:
$query = "select category_id,category_name from category";
$result = $this->Dbmodel->customQueryResult($query);
$query = "select location,location_name from sub_category";
$result_one = $this->Dbmodel->customQueryResult($query);
$query = "select category_date,category_month from other_category";
$result_two = $this->Dbmodel->customQueryResult($query);
here i am calling mysql server 3 times to execute my query and getting the result thereby..
now i am thinking how can i reduce mysql call so that all these 3 query gets executed in one single query so making only 1 call to mysql server and displaying all different results to user using php
how can i do this.. any help or suggestion would be a great help.. thanks in advance
What you've described is an SQL UNION.
Below is an example query you could use to achieve your goal:
SELECT category_id,category_name FROM category
UNION
SELECT location,location_name FROM sub_category
UNION
SELECT category_date,category_month FROM other_category
Example usage:
$query = 'SELECT category_id, category_name FROM category
UNION
SELECT location, location_name FROM sub_category
UNION
SELECT category_date, category_month FROM other_category';
$result = $this->Dbmodel->customQueryResult($query);
echo 'CategoryID: ' . $result['category_id'] . '<br />';
echo 'Category Name: ' . $result['category_name'] . '<br />';
echo 'Location: ' . $result['location'] . '<br />';
echo 'Location Name: ' . $result['location_name'] . '<br />';
echo 'Category Date: ' . $result['category_date'] . '<br />';
echo 'Category Month: ' . $result['category_month'];
Keep in mind, in case you need to select fields with identical names from different tables to use SQL aliases. An example of an alias:
SELECT category_id AS `catID` FROM category
Instead of $result['category_id'], you would use $result['catID'] instead.
As you are saying none of the tables are related, you have to fetch 3 queries.
You shouldn't combine queries, if there is no any relation. Otherwise it will give you ambiguous data.
We use sub-queries, joins when there is some relation to minimize queries.
Anyways you can get 3 queries result, if 1st, 2nd column have same data type and you can identify from 3rd column it's table name.
SELECT category_id,category_name, 'category' FROM category
UNION
SELECT location,location_name, 'sub_category' FROM sub_category
UNION
SELECT category_date,category_month, 'other_category' FROM other_category
THIS WILL BE EXACT QUERY
$query = "select category.category_id,category.category_name, sub_category.location,sub_category.location_name,other_category.category_date,other_category.category_month from category,sub_category,other_category";
You can use joint properties something like that.
$query = "select * from category, sub_category, other_category";
Note: on *, you can read this question MySQL - specific columns on join?
If the tables are related you could use joins. If that not the case you could use mysql UNION
It would be something like ...
$query = "select category_id,category_name from category UNION select location,location_name from sub_category UNION select category_date,category_month from other_category";
If all 3 Query have same data then we can Combine all 3 queries, Otherwise it would be not useful.
The Other way, Would be as Follows
Select c.category_id, c.category_name,
l.location,l.location_name,
o.category_date,o.category_month
from category C,
sub_category l,
other_category o
But Above would does get the Meaningful Data.

limit number of rows returned after executing a query

I am using ZEND MVC framework and after executing a query in my modal part (table section) the query returns 12 rows. I am passing the returned rows in the service section and further on passing the result to controller which would give me the final view for front end.
I want to limit the number of rows to be 3 in my view section. I cant use LIMIT 3 in my query since I am further interactiing with other queries and comparing the result so I need to have all 12 rows. Would it be possible to somehow put the limit in the service section?
Here is my code. Although I don't need to put every bit of my code but this would give an clear idea.
Modal (table part)
public function getJobTopStatements( UserJobEntity $activeJob, $intervalInMonths = NULL ){
if($intervalInMonths){
$interval = ' AND ss.datetime < ADDDATE( NOW(), INTERVAL -'.$intervalInMonths.' MONTH) ';
}
$testQuestionTable = $this->getServiceLocator()->get('testQuestionTable');
$questionAnswerTable = $this->getServiceLocator()->get('questionAnswerTable');
$testAnswerTable = $this->getServiceLocator()->get('testAnswerTable');
$query = 'SELECT
t.id,
t.text,
t.key,
s.answer
FROM '. $testQuestionTable->getTable() .' AS t
LEFT JOIN '. $questionAnswerTable->getTable() .' as s ON (s.testQuestionId = t.id)
LEFT JOIN '. $testAnswerTable->getTable() .' as m ON (m.id = s.testAnswerId AND
m.id = (SELECT MAX(ss.id)
FROM ' . $testAnswerTable->getTable() . ' as ss
WHERE ss.userJobId = '. $activeJob->getId() .'
'.$interval.'
)
)
WHERE m.userJobId = '. $activeJob->getId() .'
GROUP BY t.id
ORDER BY m.id DESC, s.answer DESC';
return $this->adapter->query($query, 'execute')->toArray();
}
This query returns 12 rows and I am passing the result into service section as follows
public function getActiveJobTopStatements(){
$activeJob = $this->userService->getUserActiveJob();
if(!$activeJob){
return array();
}
$result = $this->testAnswerTable->getJobTopStatements( $activeJob );
return $result;
}
and finally the controller part return this view
$view->jobTopStatements = $testAnswerService->getActiveJobTopStatements();
Is there any way I can put limit in the service section so that it will only pass 3 rows instead of 12?

mysql query not returning result if data is not in table

Here is the query that almost works:
$query = '';
$query .= ' SELECT highway_code.charge_id,
highway_code.act_abbr,
highway_code.short_form_wording,
highway_code.section,
highway_code.set_fine,
highway_code_arrest_jail_tow.demerits
';
$query .= ' FROM highway_code, highway_code_arrest_jail_tow ';
$query .= ' WHERE highway_code.charge_id = ? ';
$query .= ' AND highway_code.section = highway_code_arrest_jail_tow.section ';
$query .= ' AND highway_code.act_abbr = highway_code_arrest_jail_tow.act_abbr ';
The problem is that not all highway code charges have demerits, thus any charges without demerits are not returned, even though all the other fields apply. I would like to have all charges returned regardless if there is a value in highway_code_arrest_jail_tow.
The use of comma-separated tables in the FROM clause as you have it, with an equality condition between the related columns implies an INNER JOIN. To enforce all records being returned from the primary table regardless of the presence of related records in the related table, use a LEFT JOIN instead.
I'll replace your implicit inner join with an explicit LEFT JOIN:
SELECT
highway_code.charge_id,
highway_code.act_abbr,
highway_code.short_form_wording,
highway_code.section,
highway_code.set_fine,
highway_code_arrest_jail_tow.demerits
FROM
highway_code
LEFT JOIN highway_code_arrest_jail_tow
/* Two relating conditions belong in the ON clause */
ON highway_code.section = highway_code_arrest_jail_tow.section
AND highway_code.act_abbr = highway_code_arrest_jail_tow.act_abbr
WHERE
/* and the filtering condition remains in the WHERE */
highway_code.charge_id = ?

Mysql array and data

Mysql query and PHP code that I'm using to get users from the database that meet certain criteria is:
$sql = mysql_query("SELECT a2.id, a2.name FROM members a2 JOIN room f ON f.myid = a2.id
WHERE f.user = 1 AND a2.status ='7' UNION SELECT a2.id, a2.name FROM members a2
JOIN room f ON f.user = a2.id WHERE f.myid = 1 AND a2.status ='7' GROUP BY id")
or die(mysql_error());
while ($r = mysql_fetch_array($sql))
{
$temp[] = '"'.$r[0].'"';
}
$thelist = implode(",",$temp);
The query that follows get the list of members with new galleries by using array from the previous query.
$ft = mysql_query("SELECT id, pic1 FROM foto WHERE id IN ($thelist) AND
pic1!='' ORDER BY date DESC LIMIT 10");
while ($f = mysql_fetch_array($ft))
{
echo $f['id']." - ".$f['pic1']."<br/>";
}
These queries working fine but I need to get the name for every user listed in second query. This data is in the first query in the column name. How can I get it listed beside '$f['id']." - ".$f['pic1']'?
While I might just alter the first query to pull the galleries at the same time, or change the second query to join and get the name, you could keep the same structure and change a few things:
In the loop after the first query when building $temp[], also build a lookup table of user id to user name:
$usernames[$r[0]] = $r[1];
Then in your output loop, use the id (assuming they are the same!) from the second query to call up the user name value you stored:
echo $f['id'] . " - " . $f['pic1'] . " - " . $usernames[$f['id']] . "<br/>";

Categories