SQL + Ion Auth + CodeIgniter? - php

I have the following SQL:
SELECT (
(SELECT SUM(vote_score)
FROM question_votes
JOIN questions
ON vote_question = q_id
JOIN users
ON q_author = users.id
WHERE q_author` = users.id)
+
(SELECT SUM(vote_score)
FROM answer_votes
JOIN answers
ON vote_answer = a_id
JOIN users
ON a_author = users.id
WHERE a_author = users.id)) AS rep
and I want it to be added here (Ion Auth's method):
$this->db->select(
array(
$this->tables['users'].'.*',
$this->tables['groups'].'.name AS '. $this->db->protect_identifiers('group'),
$this->tables['groups'].'.description AS '. $this->db->protect_identifiers('group_description'),
"(SELECT COUNT(`a_author`) FROM `answers` WHERE a_author = users.id) + (SELECT COUNT(`q_author`) FROM `questions` WHERE q_author = users.id ) AS total_posts",
"SELECT
((SELECT SUM(vote_score)
FROM question_votes
JOIN questions
ON vote_question = q_id
JOIN users
ON q_author = users.id
WHERE q_author` = users.id)
+
(SELECT SUM(vote_score)
FROM answer_votes
JOIN answers
ON vote_answer = a_id
JOIN users
ON a_author = users.id
WHERE a_author = users.id)) AS rep"
)
);
but I get the followin error:

Did you read the error message?
You have a (`) where shouldn't be any.
Change this: WHERE q_author' = users.id for this: WHERE q_author = users.id

Related

how to write a left join for make loop

I want to write this code in one query with left join statement. Currently I use php for loop this query but its not good and is too slow
It's app that have like and dislike option. I want number of every user's like
public function getUserLikedCount($id) {
$query = $this->db->query(
"SELECT * FROM `users`, post, `like`
WHERE users.id = post.post_user_id
AND like.like_post_id = post.post_id
AND users.id = ?
AND post.post_is_active = 1", array($id)
);
return $query->num_rows();
}
thanks
Try like it ( I don't know your table like structure):
$sql = 'SELECT u.id AS `user_id`
COUNT(p.post_id) AS `liked_cnt` <-- or like.id ( if this field exists)
FROM `post` AS p
LEFT JOIN `users` AS u
ON ( u.id = p.post_user_id )
LEFT JOIN `like` AS l
ON ( l.like_post_id = p.post_id )
WHERE p.post_is_active = 1
AND l.status = 1 <-- "liked"
GROUP BY u.id ';
Try this :
$query = $this->db->query(
"SELECT * FROM `users` u
LEFT JOIN post p ON u.id = p.post_user_id AND u.id =?
LEFT JOIN like l ON l.like_post_id = p.post_id AND p.post_is_active = 1
", array($id)

Sort mysqli from a many-to-many table

I'm trying to make a internal web based message system, with a *amp system, primarily for learning purposes. I don't know if this is a trivial topic, but I'm having difficulties so please bear with me.
The goal is to list all the contacts ordered by the last message sent / received.
Currently without sorting it the SQL looks like this
$query = "SELECT username, user.id as user_id,
(SELECT COUNT(message_read)
FROM message_user
WHERE message_read = 0
AND sent_id = user_id
AND receive_id = {$userId}) as unread
FROM user
WHERE user.id IN
(SELECT contact_id FROM allowed_contact WHERE user_id = {$userId})
;";
The structure of the tables are:
The user table has an id,
That links to the message_user table which has a sent_id and a receive_id,
The message_user has a message_id that corresponds to the message.id,
The message table has a timestamp.
I would like this to be done in SQL but if it comes down to PHP I resign to resort to that.
This works.
SELECT `u`.`id` AS user_id, username,
(SELECT COUNT(message_user.message_read)
FROM message_user
WHERE message_user.message_read = 0
AND sent_id = user_id
AND receive_id = {$userId}) as unread
FROM `user` AS `u`
LEFT JOIN `message_user` AS `mu`
ON
(CASE WHEN `u`.`id` != {$userId}
THEN `u`.`id` = `mu`.`sent_id`
WHEN `mu`.`sent_id` = {$userId} AND `mu`.`receive_id` = {$userId}
THEN `u`.`id` = `mu`.`sent_id`
END)
OR
(CASE WHEN `u`.`id` != {$userId}
THEN `u`.`id` = `mu`.`receive_id`
END)
LEFT JOIN `message` AS `m` ON `m`.`id` = `mu`.`message_id`
WHERE u.id IN
(SELECT contact_id FROM allowed_contact WHERE user_id = {$userId})
GROUP BY u.id
ORDER BY MAX(`m`.`timestamp`) DESC;
This broke down the problem I was having.
#Andreas thanks for time and help.
Use 2 LEFT JOIN with a DISTINCT (untested):
SELECT DISTINCT `u`.`id`
FROM `user` AS `u`
LEFT JOIN `message_user` AS `mu` ON `u`.`id` = `mu`.`sent_id` OR `u`.`id` = `mu`.`receive_id`
LEFT JOIN `message` AS `m` ON `m`.`id` = `mu`.`message_id`
ORDER BY `m`.`timestamp` DESC;

How to write Subquery in Select statement laravel 5.1?

How to write this query in laravel 5.1
SELECT
(SELECT firstname FROM registration_details a INNER JOIN users b
ON a.id = b.registerid
WHERE c.patientid = b.id ) AS patient,
(SELECT firstname FROM registration_details a INNER JOIN users b
ON a.id = b.registerid
WHERE c.doctorid = b.id ) AS doctor,
c.`appoinmentdate`
FROM `appoinments` c
I tried like this But i get Undefined property: stdClass::$id error
DB::table('appoinments')
->select(DB::raw(
"(SELECT firstname FROM registration_details INNER JOIN users ON registration_details.id = users.registerid WHERE appoinments.patientid = users.id) AS patient",
"(SELECT firstname FROM registration_details INNER JOIN users ON registration_details.id = users.registerid WHERE appoinments.doctorid = users.id) As doctor",
"appoinments.appoinmentdate",
"appoinments.id",
"(SELECT timings FROM appoinment_time WHERE appoinment_time.id = appoinments.appoinment_time) AS apptime ",
"(SELECT branchname FROM branches WHERE branches.id = appoinments.branchcode) AS branch"))
->get();
Finally got the answer. Thanks to all who try for me.
$appoinment = DB::table('appoinments')->select(DB::raw("(SELECT firstname FROM registration_details INNER JOIN users ON registration_details.id = users.registerid WHERE appoinments.patientid = users.id) AS patientid"));
$appoinment = $appoinment->addSelect(DB::raw("(SELECT firstname FROM registration_details INNER JOIN users ON registration_details.id = users.registerid WHERE appoinments.doctorid = users.id) As doctorid"));
$appoinment = $appoinment->addSelect(DB::raw("appoinments.appoinmentdate"));
$appoinmentlist = $appoinment3->addSelect(DB::raw("appoinments.id"))->get();

Select approved comments and unapproved comments of current user MySQL PHP

I'm new to mysql and I have a problem with selecting data from mysql database:
$post_id = 3;
$current_user_id = 1;
$query = "SELECT `comments`.*, `users`.`username`, `users`.`image` FROM (`comments`)
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`id`
WHERE `comments`.`post_id` = '$post_id'
AND `comments`.`status` = 1
AND `users`.`status` = 1
ORDER BY `comments`.`date` desc";
This select, selects all approved comments from database, but also, in this select, I need all unapproved comments of $current_user_id,
Result must look like:
[all approved post comments] + [all unapproved post comments of $current_user_id]
not sure if this will really work, but just give a try and see. I can't test the query since we don't have the schema.
SELECT `comments`.*, `users`.`username`, `users`.`image` FROM (`comments`)
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`id`
WHERE `comments`.`post_id` = '$post_id'
AND (
(`comments`.`status` = 1 AND `users`.`status` = 1)
OR
( `comments`.`status` = 0 AND `users`.`id`= '$current_user_id' )
)
ORDER BY `comments`.`date` desc
What I thought is select all the approved comments OR ( comments that are not approved, but from this user ). You might have to alter the query till you get what you really needed, I'm just giving you the idea, not the exact query. Hope this will help you.
SELECT `comments`.*, `users`.`username`, `users`.`image` FROM (`comments`)
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`id`
WHERE `comments`.`post_id` = '$post_id'
AND `comments`.`status` = 1
AND `users`.`status` = 1
UNION ALL
SELECT `comments`.*, `users`.`username`, `users`.`image` FROM (`comments`)
LEFT JOIN `users` ON `comments`.`user_id` = `users`.`id`
WHERE `comments`.`post_id` = '$post_id'
AND `comments`.`status` = 0
AND `users`.`id` = '$current_user_id'
ORDER BY `comments`.`date` desc

GROUP first and second level friends

Lets say that given a song_id and a uid, we would like to know all friends (direct friends and friends of frinds) that like the same song:
This is how we are doing it:
public function get_song_mates($uid, $song_id, $current_only = true, $limit = PHP_INT_MAX)
{
$sql = "SELECT *
FROM (
(
SELECT users . * , '1st' AS `level`, 1 AS `level_i`
FROM songs
JOIN users ON users.id = songs.user_id
JOIN friends AS my_friend ON my_friend.fid = users.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."')
UNION (
SELECT second_friend . * , '2nd' AS `level`, 2 AS `level_i`
FROM songs
JOIN users AS second_friend ON second_friend.id = songs.user_id
JOIN friends ON friends.uid = second_friend.id
JOIN users AS first_friend ON first_friend.id = friends.fid
JOIN friends AS my_friend ON my_friend.fid = first_friend.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."'
AND second_friend.id NOT IN
(
SELECT users.id
FROM songs
JOIN users ON users.id = songs.user_id
JOIN friends AS my_friend ON my_friend.fid = users.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."'
)
) ORDER BY `level_i` ASC, firstname, lastname
) AS friend
GROUP BY id ORDER BY `level_i`";
$users = $this->getFromSql($sql);
return $users;
}
But please note we had to add:
AND second_friend.id NOT IN...
to prevent showing same user as direct friend and as a friend of friend.. i am pretty sure i need to make use of GROUP BY, but i just can't get with the right syntax. any clue here?
-EDIT-
friends(uid, fid)
songs(id, user_id, song_id)
users(id, frist_name, last_name)
Fixed it like this:
public function get_song_mates($uid, $song_id, $current_only = true, $limit = PHP_INT_MAX)
{
$sql = "SELECT DISTINCT *
FROM (
(
SELECT users . * , '1st' AS `level`, 1 AS `level_i`
FROM songs
JOIN users ON users.id = songs.user_id
JOIN friends AS my_friend ON my_friend.fid = users.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."')
UNION (
SELECT DISTINCT second_friend . * , '2nd' AS `level`, 2 AS `level_i`
FROM songs
JOIN users AS second_friend ON second_friend.id = songs.user_id
JOIN friends ON friends.uid = second_friend.id
JOIN users AS first_friend ON first_friend.id = friends.fid
JOIN friends AS my_friend ON my_friend.fid = first_friend.id
AND my_friend.uid = '".$uid."'
WHERE song_id = '".$song_id."'";
$users = $this->getFromSql($sql);
return $users;
}

Categories