LIMIT results on specific table when using LEFT JOIN - php

Below is my query. I would like to get only 10 posts from post table. However it LIMIT 10 below doesn't limit the results in posts table but it does on another table.
Can anyone help me to fix the query? I really appreicate your help.
SELECT posts.id , posts.cat_id , posts.school_id , posts.campus_id , posts.status , posts.priority , posts.title , posts.content , posts.phone , posts.email , posts.tags , posts.zip , posts.price_new , posts.price_old , posts.reviewed_by , posts.reviewed_date , posts.updated_date , posts.posted_date , posts.expired_date , posts.ip_address , schools.school_name, campuses.campus_name , meta.meta_key , meta_value , images.img_name
FROM posts LEFT JOIN
meta
ON posts.id = meta.post_id LEFT JOIN
images
ON posts.id = images.post_id LEFT JOIN
schools
ON posts.school_id = schools.id LEFT JOIN
campuses
ON posts.campus_id = campuses.id
ORDER BY posts.updated_date DESC LIMIT 10

One method is to use a subquery:
SELECT p.id , p.cat_id, p.school_id, p.campus_id , p.status,
p.priority, p.title, p.content, p.phone, p.email, p.tags, p.zip,
p.price_new, p.price_old, p.reviewed_by, p.reviewed_date,
p.updated_date, p.posted_date, p.expired_date, p.ip_address,
s.school_name, c.campus_name,
m.meta_key, m.meta_value,
i.img_name
FROM (SELECT p.*
FROM posts p
ORDER BY p.updated_date DESC
LIMIT 10
) p LEFT JOIN
meta m
ON p.id = m.post_id LEFT JOIN
images i
ON p.id = i.post_id LEFT JOIN
schools s
ON p.school_id = s.id LEFT JOIN
campuses c
ON p.campus_id = c.id;
Note that the use of table aliases makes the query easier to write, read, and understand.

Related

How to JOIN these 3 tables

I have the following JOIN query already done:
$stmt = $cxn->prepare('SELECT p.post_id, p.reply_to, p.parent_id, p.post_path, p.user_id, p.content, p.datetime, p.total_likes, p.total_replies, p.total_reposts, u.username, u.display_name FROM posts p LEFT JOIN users u ON p.user_id = u.user_id WHERE p.user_id IN (SELECT following_id FROM follows WHERE user_id = ?) AND p.removed != 1 ORDER BY p.datetime DESC LIMIT 26');
$stmt->bind_param('i', $user_info[0]);
$stmt->execute();
I have another query that's only purpose is to check if a row exists or not:
$stmt = $cxn->prepare('SELECT COUNT(like_id) FROM likes WHERE post_id = ? AND user_id = ?');
$stmt->bind_param('ii', $row['post_id'], $user_info[0]); // $row['post_id'] is the value of p.post_id from the first query
$stmt->execute();
How would I join the second query into the first one? I've never joined 3 tables so I'm unsure of the procedure.
Thanks.
Joining three tables in a query is like joining two, except... you join three.
Basically it would go something like this:
SELECT p.post_id (...), u.username (...), COUNT(l.like_id) AS nbOfLikes
FROM posts p
LEFT JOIN users u ON p.user_id = u.user_id
LEFT JOIN likes l ON l.post_id = p.post_id AND l.user_id = u.user_id
WHERE p.user_id IN
(SELECT following_id
FROM follows
WHERE user_id = ?)
AND p.removed != 1
ORDER BY p.datetime DESC
LIMIT 26;
-- Actually I think a UNION would perhaps be more adapted to your need concerning the likes table.
If you always have the user_id filled into your table posts and it's a foreign key, avoid to use a left join statement, you can get a better performance using join statement. To join 3 or more tables you can just add the join statement:
SELECT
p.post_id
, p.reply_to
, p.parent_id
, p.post_path
, p.user_id
, p.content
, p.datetime
, p.total_likes
, p.total_replies
, p.total_reposts
, u.username
, u.display_name
FROM posts p
JOIN users u ON p.user_id = u.user_id WHERE p.user_id IN (SELECT following_id FROM follows
JOIN TABLE_2 ON TABLE_2.id = posts.TABLE_id
JOIN TABLE_3 ON TABLE_3.id = posts.TABLE_id
...
WHERE
user_id = ?)
AND p.removed != 1
ORDER BY p.datetime DESC
LIMIT 26

MYSQL customizable join and select

i want to use JOIN categories c ON c.id = i.category if post_type is 1 and i want to have c.title AS category_name, in SELECT otherwise JOIN categories c ON c.id = i.category and c.title AS category_name, must be not worked in query , i'm using case for join but my sql command is not correct. please help me. in all description my quastion means is how to change this below command to if post_type is 1 join must be not work
SELECT SQL_CALC_FOUND_ROWS
i. * ,
c.title AS category_name,
s.title AS status_title,
i.thumb_image,
CONCAT( u.name, ' ', u.family ) AS author
FROM contents i
LEFT JOIN categories c
ON i.category = CASE post_type WHEN 1 then c.id END
JOIN users u ON u.id = i.posted_by
JOIN status_topics s ON s.id = i.t_status
WHERE i.id = 2
I would always do the LEFT JOIN and put a condition on the column itself:
SELECT SQL_CALC_FOUND_ROWS
i. * ,
IF(i.post_type = 1, c.title, NULL) AS category_name,
s.title AS status_title,
i.thumb_image,
CONCAT( u.name, ' ', u.family ) AS author
FROM contents i
LEFT JOIN categories c ON i.category = c.id
JOIN users u ON u.id = i.posted_by
JOIN status_topics s ON s.id = i.t_status
WHERE i.id = 2

SQL multiple joins SELECT query with MAX()

The following query select the subforums from the database and the last posts in each one of them.
SELECT
forums.*,
MAX(posts.id),
posts.title AS lastmsgtitle,
posts.timee AS lastmsgtime,
posts.useraid AS lastmsguseraid,
posts.useradn AS lastmsguseradn,
users.photo AS lastmsgphoto
FROM forums
LEFT JOIN posts
ON(posts.forumid = forums.id)
LEFT JOIN users
ON(posts.useraid = users.id)
WHERE forums.relatedto='$forumid'
and posts.type='post'
GROUP BY forums.id
ORDER BY `id` DESC
The only problem, the query not select the last post, any ideas why?
FORUMS 1
POSTS 2
I would suggest using a subquery to select the max(id) for each post.
SELECT
f.*, -- replace the f.* with the columns that you need to return
p1.MaxId,
p2.title AS lastmsgtitle,
p2.timee AS lastmsgtime,
p2.useraid AS lastmsguseraid,
p2.useradn AS lastmsguseradn,
u.photo AS lastmsgphoto
FROM forums f
LEFT JOIN
(
select MAX(id) MaxId, forumid
from posts
group by forumid
) p1
ON p1.forumid = f.id
LEFT JOIN posts p2
ON p2.forumid = f.id
and p1.MaxId = p2.id
and p2.type='post'
LEFT JOIN users u
ON p2.useraid = u.id
WHERE f.relatedto='$forumid'
ORDER BY `id` DESC

Complicated mysql join for student listing

I have this problem with my query. The goal of the query is to display all students, whether they are in the aanweezigheid table or not.
This is my query:
SELECT
s.studentNaam
, s.studentAchterNaam
, s.studentStamNummer
, s.klasID
, k.klasNaam
, k.klasID
, a.studentID
, a.aanwezigTijdAan
, a.aanwezigTijdAf
, a.aanwezigDag
, a.aanwezigStatus
FROM studenten AS s
LEFT JOIN klassen AS k ON s.klasID=k.klasID
LEFT JOIN aanweezigheid AS a ON a.studentID=s.studentID
WHERE k.klasNaam = 'MD2a'
AND a.aanwezigDag='2012-08-28'
ORDER BY s.studentAchterNaam ASC
Any ideas?
Move your WHERE conditions to LEFT JOIN ON clause:
SELECT ...
FROM studenten AS s
LEFT JOIN klassen AS k
ON s.klasID=k.klasID
AND k.klasNaam = 'MD2a'
LEFT JOIN aanweezigheid AS a
ON a.studentID=s.studentID
AND a.aanwezigDag='2012-08-28'
ORDER BY s.studentAchterNaam ASC;
just move your "a" dependency into the ON term. That way you won't be filtering anything out in your WHERE:
SELECT
s.studentNaam
, s.studentAchterNaam
, s.studentStamNummer
, s.klasID
, k.klasNaam
, k.klasID
, a.studentID
, a.aanwezigTijdAan
, a.aanwezigTijdAf
, a.aanwezigDag
, a.aanwezigStatus
FROM studenten AS s
LEFT JOIN klassen AS k ON s.klasID=k.klasID
LEFT JOIN aanweezigheid AS a ON a.studentID=s.studentID
AND a.aanwezigDag='2012-08-28'
WHERE k.klasNaam = 'MD2a'
ORDER BY s.studentAchterNaam ASC

Filter MySQL result w/ empty row

I have searched high and low to filter my mysql query but WHERE NOT NULL does not work. I hope somebody could help me. I have some columns that are empty named 'path'. And I want to filter these out.
My query:
SELECT
p.path, p.title, p.body, p.post_date, u.username FROM pages p
LEFT JOIN users u ON p.post_author = u.id
ORDER BY p.id ASC
How can I get this done? Thanks.
SELECT
p.path, p.title, p.body, p.post_date, u.username
FROM pages p
LEFT JOIN users u ON p.post_author = u.id
WHERE
p.path IS NOT NULL AND
p.path <> ''
ORDER BY p.id ASC
So does this help or you are asking something different?
try with php to check the empty field:
$query = "SELECT
p.path, p.title, p.body, p.post_date, u.username FROM pages p
LEFT JOIN users u ON p.post_author = u.id
ORDER BY p.id ASC";
$result = mysql_query($query);
while( $row = mysql_fetch_assoc($result) ){
// Check for empty record
if( !empty($row['path']) ){
echo $row['path'];
}
}
Try this one, this might work.
SELECT
p.path, p.title, p.body, p.post_date, u.username FROM pages p
LEFT JOIN users u ON p.post_author = u.id
WHERE p.path IS NOT NULL AND p.path <> ''
ORDER BY p.id ASC

Categories