I have 3 tables they are...
posts_deletedPosts
posts_archivedPosts
posts_newPosts
I am writing a function which allows users to see all of their posts and so I want to do a join query to pull all the data from these three tables back in one query.
All three tables has the exact same columns I want to get back, and they are...
title
category
dateCreated
alias
The query i've written so far I think should work, but when I go to use bind param I get this error.
Warning: mysqli_stmt::bind_result() [mysqli-stmt.bind-result]: Number of bind variables doesn't match number of fields in prepared statement
My query looks like as follows...
$stmt = $this->conx->prepare("SELECT
dp.title, dp.category, dp.dateCreated, dp.alias,
ap.title, ap.category, ap.dateCreated, ap.alias,
np.title, np.category, np.dateCreated, np.alias
FROM posts_deletedPosts AS dp
INNER JOIN posts_archivedPosts AS ap
ON dp.author = ap.author
INNER JOIN posts_newPosts AS np
ON dp.author = np.author
WHERE dp.author = ?
LIMIT 5");
I'm pretty new to web dev but I thought it would be possible to carry out a join like this and return one large dataset. I did use 3 select queries before but I want to build some pagination using AJAX and so I need this data in one complete set preferably.
This is how i bind the parameter
$stmt->bind_param("i",$uid);
You don’t need JOINs, you need UNIONs:
SELECT title FROM posts_deletedPosts WHERE author=...
UNION
SELECT title FROM posts_archivedPosts WHERE author=...
UNION
SELECT title FROM posts_newPosts WHERE author=...
Related
I am having relational database and trying to execute following query up to 3 tables It is giving me correct results i.e. 248 records of students in institute id 910, but when I try to make a query having more than 3 tables it gives me 19000+ results.
SELECT *
FROM Student,StudentRegistration,RefStudentType,RefGender,SubjectCategory
WHERE Student.student_id=StudentRegistration.student_student_id
AND StudentRegistration.reg_student_type_std_type_id = RefStudentType.std_type_id
AND Student.student_gender_gender_id = RefGender.gender_id
AND StudentRegistration.reg_student_subjectCat_sub_cat_id=SubjectCategory.sub_cat_id
AND Student.student_institute_inst_id=910;
`
Tried with JOIN as well but same 19000+ records incorrect results
SELECT * FROM Student INNER JOIN StudentRegistration ON student_id=student_student_id INNER JOIN RefReligion ON RefReligion.religion_id=Student.student_religion_religion_id INNER JOIN RefStudentType ON RefStudentType.std_type_id=StudentRegistration.reg_student_type_std_type_id WHERE student_institute_inst_id=910;
Any solution, query logical errors or something new
I think this is due to having several records for one data. For example, there might be several records in the SubjectCategory table for id = '910'
It is best to use left/right/inner/outer joins without using from tbl1, tbl2
What I suggest is to check the tables one by one with the id.
I have two tables tableOne = 90K data and tableTwo = 100k data, i will look for the duplicate numbers on both tables with the given conditions and the matching must be 1:1 if multiple match are on the other table only one will be tagged as match (given that the data on both tables has match data).
I have this select statement below, but when i run it on my local xampp and even on CMD the screen freezes after i press enter then it takes hours before it returns an error out of memory. Hope you can help me with this.
SELECT rNum,
cDate,
cTime,
aNumber,
bNumber,
duration,
tag,
aNumber2,
bNumber2,
'hasMatch',
concatDate,
timeMinutes
FROM tableOne a
LEFT JOIN
tableTwo b ON a.aNumber2 = b.aNumber2
AND a.bNumber2 = b.bNumber2
WHERE a.hasMatch = 'valid'
AND (a.duration - b.duration) <= 3
AND (a.duration - b.duration) >= -3
AND TIMEDIFF(a.concatDate,b.concatDate) <= 3
AND TIMEDIFF(a.concatDate,b.concatDate) >= -3
Thank you In advance.
If you're doing 1:1 relationship with two tables then I think you should probably go with INNER JOIN rather than LEFT JOIN
Secondly, your query doesn't seem to be indexed properly. So, better would be using EXPLAIN SELECT ... to see the profile of SQL and create INDEXES for Filters.
in your SELECT you have aNumber2 and based on your join rule both table a and table b have aNumber2 column. it's a problem. if two table have a column with the same name, on select you should specify the table.
for example like this
SELECT a.aNumber2 as a_number2,....
in your query the same problem exists for other columns like duration and concatDate
another thing is you should use INNER JOIN in your case instead of LEFT JOIN.
if you final result have many rows(thousands), take them step by step... add LIMIT to your example and take 100 result each time.
I've been racking my brain for hours trying work out how to join these two queries..
My goal is to return multiple venue rows (from venues) based on certain criteria... which is what my current query does....
SELECT venues.id AS ven_id,
venues.venue_name,
venues.sub_category_id,
venues.score,
venues.lat,
venues.lng,
venues.short_description,
sub_categories.id,
sub_categories.sub_cat_name,
sub_categories.category_id,
categories.id,
categories.category_name,
((ACOS( SIN(51.44*PI()/180)*SIN(lat*PI()/180) + COS(51.44*PI()/180)*COS(lat*PI()/180)*COS((-2.60796 - lng)*PI()/180)) * 180/PI())*60 * 1.1515) AS dist
FROM venues,
sub_categories,
categories
WHERE
venues.sub_category_id = sub_categories.id
AND sub_categories.category_id = categories.id
HAVING
dist < 5
ORDER BY score DESC
LIMIT 0, 100
However, I need to include another field in this query (thumbnail), which comes from another table (venue_images). The idea is to extract one image row based on which venue it's related to and it's order. Only one image needs to be extracted however. So LIMIT 1.
I basically need to insert this query:
SELECT
venue_images.thumb_image_filename,
venue_images.image_venue_id,
venue_images.image_order
FROM venue_images
WHERE venue_images.image_venue_id = ven_id //id from above query
ORDER BY venue_images.image_order
LIMIT 1
Into my first query, and label this new field as "thumbnail".
Any help would really be appreciated. Thanks!
First of all, you could write the first query using INNER JOIN:
SELECT
...
FROM
venues INNER JOIN sub_categories ON venues.sub_category_id = sub_categories.id
INNER JOIN categories ON sub_categories.category_id = categories.id
HAVING
...
the result should be identical, but i like this one more.
What I'd like to do next is to JOIN a subquery, something like this:
...
INNER JOIN (SELECT ... FROM venue_images
WHERE venue_images.image_venue_id = ven_id //id from above query
ORDER BY venue_images.image_order
LIMIT 1) first_image
but unfortunately this subquery can't see ven_id because it is evaluated first, before the outer query (I think it's a limitation of MySql), so we can't use that and we have to find another solution. And since you are using LIMIT 1, it's not easy to rewrite the condition you need using just JOINS.
It would be easier if MySql provided a FIRST() aggregate function, but since it doesn't, we have to simulate it, see for example this question: How to fetch the first and last record of a grouped record in a MySQL query with aggregate functions?
So using this trick, you can write a query that extracts first image_id for every image_venue_id:
SELECT
image_venue_id,
SUBSTRING_INDEX(
GROUP_CONCAT(image_id order by venue_images.image_order),',',1) as first_image_id
FROM venue_images
GROUP BY image_venue_id
and this query could be integrated in your query above:
SELECT
...
FROM
venues INNER JOIN sub_categories ON venues.sub_category_id = sub_categories.id
INNER JOIN categories ON sub_categories.category_id = categories.id
INNER JOIN (the query above) first_image on first_image.image_venue_id = venues.id
INNER JOIN venue_images on first_image.first_image_id = venue_images.image_id
HAVING
...
I also added one more JOIN, to join the first image id with the actual image. I couldn't check your query but the idea is to procede like this.
Since the query is now becoming more complicated and difficult to mantain, i think it would be better to create a view that extracts the first image for every venue, and then join just the view in your query. This is just an idea. Let me know if it works or if you need any help!
I'm not too sure about your data but a JOIN with the thumbnails table and a group by on your large query would probably work.
GROUP BY venues.id
What is the best way to get labels of id's .
Here is the problem i'm facing .
I have a many tables that only contains id's (subject_id , level_id , place_id , etc..)
What is the best way to display the labels of those id's without making a complex sql query when displaying (have minimum of 6'ids) ?
The other options which is not very nice to do would be to call get_label(id,table,lang)
but of course you can see the problem for each column (Total queries = column * rows)
Any better solution or i'm stuck without doing the join on 6 tables ?
If it's helps i'm using kohana
here is what i have ...
and the subject table for the subject_id :
I have for every field_id a table that correspond .
In term of performance which is better making a join or just calling a query to get the specific label when needed . ?
You want to use a SQL JOIN for this.
SELECT t1.*, t2.subject_en, ...
FROM table1 t1
JOIN table2 t2 ON (t2.id = t1.subject_id)
A JOIN has a much better performane - you have only a single query which can be properly optimized by the database engine while doing a SELECT while iterating over the rows from the initial query would give you n+1 separate queries.
I am trying to query 2 tables in a database, each query having nothing to do with each other, other then being on the same page.
Query 1 - The first query on the page will retrieve text and images that are found throughout the page from Table A.
Query 2 - The second query will retrieve several products with a image, description and title for each product from Table B.
I know that putting the second query inside the first query's while loop would work but of course is very inefficient.
How can I and what is the best way to retrieve all the data I need through 1 query?
Thanks,
Dane
So all you want to know is if its ok to have 2 queries on the same webpage? Its A-OK. Go right ahead. Its completelly normal. No one expects a join between table news and table products. Its normal to usetwo queries to fetch data from two unrelated tables.
Use LEFT or INNER JOIN (depends on whether you want to display records from TableA that have no correspondent records in TableB)
SELECT a.*, b.*
FROM TableA a
[LEFT or INNER] JOIN TableB b ON (b.a_id = a.id)
If there's no way to relate the two tables to each other, then you can't use a JOIN to grab records from both. You COULD use a UNION query, but that presumes that you can match up fields from each table, as a UNION requires you to select the same number/type of fields from each table.
SELECT 'pageinfo' AS sourcetable, page.id, page.images, page.this, page.that
WHERE page.id = $id
UNION
SELECT 'product' AS sourcetable, products.id, products.image, product.other, product.stuff
But this is highly ugly. You're still forcing the DB server to do two queries in the background plus the extra work of combining them into a single result set, and then you have to do extra work to dis-entangle in your code to boot.
It's MUCH easier, conceptually and maintenance-wise, to do two seperate queries instead.