sub queries order by - php

I am trying get records from question order by sub query (qcat) table. and my code is
"SELECT * FROM question
where survey_name='$_SESSION[ssn_sname]' AND
qcategory IN
( SELECT qcategory FROM qcat
WHERE client_name='$_SESSION[ssn_sname]'
GROUP BY qcategory
ORDER BY p_order
) AND
status='1' AND
survey_name LIKE'%$sname%
LIMIT $start, $limit";
But it did not get results in order.
how can i get rows order by the qcat table?

In the sub query you do not need the GROUP BY clause - This is used for aggregated functions
You also do not need the ORDER BY in the sub query - Let mysql work it out for the in bit
Add the ORDER BY for the whole query. i.e. at the end
So the SQL should be
"SELECT * FROM question
where survey_name='$_SESSION[ssn_sname]' AND
qcategory IN
( SELECT qcategory FROM qcat
WHERE client_name='$_SESSION[ssn_sname]'
) AND
status='1' AND
survey_name LIKE'%$sname%
ORDER BY p_order
LIMIT $start, $limit";
I also think that you may be able to avoid the sub query in the first place. But that would require a little thinking and a bit more knowledge about the tables.
BTW - Note the possibility of SQL injection

You need to join with the qcat table in order to be able to sort on a different column within that table. Try this:
$query = "
SELECT q.id question_id, q.*, c.*
FROM question q
INNER JOIN qcat c ON c.category = q.category
WHERE q.survey_name='$_SESSION[ssn_sname]'
AND c.client_name = '$_SESSION[ssn_sname]'
AND q.status='1'
AND q.survey_name like '%$sname%'
GROUP BY q.id
ORDER BY c.p_order
LIMIT $start, $limit";
Note: Your query is vulnerable to SQL Injection!

Related

Get Name From Another Table MySQL

I have two table in my database called
number_list and number_status
I am currently getting perfect result using below query
SELECT * FROM number_status
WHERE number = '".$_SESSION['number1']."' OR
number = '".$_SESSION['number2']."'
ORDER BY id DESC LIMIT $start, $limit
Now I want name from table number_list. Both table have number is common. I have tried some Left Join etc but I am learning MySQL yet so not getting proper result. Let me know if someone can help me for do it.
Thanks
You can use a join query as follows
SELECT s.id, s.number, l.name FROM number_list l JOIN number_status s ON l.number=s.number WHERE s.number = '".$_SESSION['number1']."' OR s.number = '".$_SESSION['number2']."' ORDER BY l.id DESC LIMIT $start, $limit
or you can directly get the name as you have the number in hand as follows
SELECT name FROM number_list WHERE number = '".$_SESSION['number1']."' OR number = '".$_SESSION['number2']."' ORDER BY id DESC LIMIT $start, $limit

Return MYSQL QUERY INVERSED

I have this query in mysql, some one know how to return an inverse query ?
mysql_query("
SELECT * FROM batepapo
WHERE tipo='$t' && lang='$l'
ORDER BY id DESC LIMIT 0,100
");
The correct code now is
SELECT s.* FROM (
SELECT t.* FROM batepapo
t WHERE t.tipo='$t' AND t.lang='$l'
ORDER BY t.id DESC LIMIT 0,100)
AS s ORDER BY s.id")
One option is to use your existing query as an inline view query, and the outer query can reorder the results.
As an example:
SELECT s.*
FROM ( SELECT t.*
FROM batepapo t
WHERE t.tipo='fooval'
AND t.lang='langval'
ORDER BY t.id DESC
LIMIT 0,100
) s
ORDER BY s.id
using union syntax:
( SELECT t.*
FROM batepapo t
WHERE t.tipo='fooval'
AND t.lang='langval'
ORDER BY t.id DESC
LIMIT 0,100
) ORDER BY id
I'm obligated to add some recommendations. 1) Consider that your existing code may be subject to SQL Injection vulnerabilities (i.e. we don't see any calls to the mysql_real_escape_string function.) and 2) The mysql_ interface is deprecated, and new code should use either PDO or mysqli interface.
mysql_query("
SELECT * FROM batepapo
WHERE tipo='$t' && lang='$l'
ORDER BY id ASC LIMIT 0,100
");
just to clarify what I was saying on spencer7593's answer.. you can also write the query like this.
using union syntax:
(SELECT t.*
FROM batepapo t
WHERE t.tipo='fooval'
AND t.lang='langval'
ORDER BY t.id DESC
LIMIT 0,100)
ORDER BY id
basically you just do the select and then order afterwards. this seems like it wouldn't work and it isn't documented in MySQL, but its obvious from the grammar:

using LIMIT and ORDER BY with LEFT JOIN in sql query

I'm a bit new to JOIN and I'm finding it difficult to understand how I can query one table with ORDER BY and LIMIT and using only ORDER BY on my JOINED 'right' table I think it is? So Basically if I was to query the two tables individually I would use these queries:
SELECT * FROM posts ORDER BY dateSubmitted DESC LIMIT ?,5
'?' standing for my bind_param() because I'm creating a pagination. Now for my 'right' Second table:
SELECT * FROM postcomments WHERE postcomments.postID = posts.ID ORDER BY dateSubmitted DESC
As far as my understanding goes to 'link' the two tables together I want to be using LEFT JOIN so that I will receive all my data from the 'left' table (being posts).
SELECT * FROM posts LEFT JOIN postcomments ON postcomments.postID = posts.ID
Now I can do this but I'm unsure where I would but my ORDER BY and LIMIT for both tables?
I've seen several different ways and I think this is what's getting me confused like I've seen this:
SELECT p.* FROM posts p ORDER BY posts.dateSubmitted DESC LIMIT ?,5
LEFT JOIN (SELECT * FROM postcomments
WHERE postscomments.postID = p.ID ORDER BY postcomments.dateSubmitted);
But I'm really unsure how to structure my query :S Any help appreciated :)
It will be at the end like this:
Select * from
(SELECT * FROM posts ORDER BY dateSubmitted DESC LIMIT ?,5) as tempPost
LEFT JOIN postcomments on (postscomments.postID = tempPost.ID)

Combine to two tables within a single query to order data

I have two tables word_term_relationships and word_posts
What I'm doing is using a while loop in order to fetch a certain record from the word_term_relationships table where a certain value is true.
$query = "SELECT object_id
FROM `word_term_relationships`
WHERE `term_taxonomy_id` = '54'";
I then use another query within the loop to use the data that was retrieved from the previous query in order to fetch data from the other table word_posts
$query2 = "SELECT post_title, post_date, post_date_gmt, guid
FROM `word_posts`
WHERE `ID` = '$post_id'";
This I can do and works fine.
The only issue is that I then need to order the results by date and time, I can do this without the while loop and using the ORDER BY function and the word_posts table.
However, I've tried to link the tables within the query like this (below) in order to order the data. But obviously it isn't correct - I just can't pinpoint within the query what is wrong.
$query = "SELECT word_term_relationships.object_id
FROM word_term_relationships
WHERE word_term_relationships.term_taxonomy_id = '54'
ORDER BY word_posts.post_date ASC";
I know the above query is missing something, I was thinking a second where after the ORDER BY word_posts.post_date ASC.
A simple INNER JOIN will solve your problem. Try this,
SELECT a.post_title,
a.post_date,
a.post_date_gmt,
a.guid
FROM word_posts a
INNER JOIN word_term_relationships b
ON a.ID = b.object_id
WHERE b.term_taxonomy_id= '54'
ORDER BY a.post_date ASC
$query = "SELECT post_title
, post_date
, post_date_gmt
, guid
FROM word_posts a INNER JOIN word_term_relationships b on a.ID = b.object_id
WHERE term_taxonomy_id = '54'
ORDER BY a.post_date ASC";

SELECT sql statement that retrieves one row from a table and many related rows from other table

I working in a poll script, i have two tables {hs_questions_q}{hs_answers_ans} the first one stored the question and the second stored its answers
i used this sql statement to retrieve the data
SELECT * FROM hs_questions_q INNER JOIN hs_answers_ans ON id_q=idq_ans WHERE active_q ='1' and home_q ='1' ORDER BY id_q DESC limit 1
what i was wonder and i can't deal with in my php code is how that this query returned the last row only from the the question table and answers table, but i need to retrieve the last row from the question table and all rows related to it from the answers table
This will return 1 row per question in the table not as the num rows of answers:
I assume the structure:
hs_questions_q (id,desc)
hs_answers_ans(id,desc)
SELECT question.desc, group_concat(hs_answers_ans.desc SEPARATOR '#')
FROM (select *
from hs_questions_q
where active_q ='1' and home_q ='1' ORDER BY id_q DESC limit 1) question
INNER JOIN hs_answers_ans ON id_q=idq_ans
group by question.id
result:
question1 | Answer1#Answer2#Answer3
Later, you can split it by '#' after retrieving the result on the php side.
You might get truncated answers if it exceeds the allowed packet size. You can solve it by,
SET SESSION group_concat_max_len = 6000(any threshold);
I think it's roughly what you're looking for:
SELECT * FROM
(select *
from hs_questions_q
where active_q ='1' and home_q ='1' ORDER BY id_q DESC limit 1) question
INNER JOIN hs_answers_ans ON id_q=idq_ans
I don't know whether active_q and home_q belong to question table or answers
Its because you are trying to grab one row and join it with more than one row of different data... I don't think that will work.
I would select the question and then use the id from the question to grab all the answers separately.
select * from hs_answer_ans where idq_ans in (select id_q from hs_questions_q where active_q ='1' and home_q ='1' ORDER BY id_q DESC limit 1)
Sorry some typo was there in comment...:)
This query should give you the desired result:
SELECT *
FROM `hs_questions_q`
INNER JOIN `hs_answers_ans` ON `id_q` = `idq_ans`
WHERE `idq_ans` = (
SELECT MAX(`id_q`)
FROM `hs_questions_q`
WHERE `active_q` ='1'
AND `home_q` ='1'
);
Hope it helps!

Categories