Help with mysql join - mysql

This is my statement for me to pull all the data of my users' friends that they have added:
$q = $dbc -> prepare("SELECT a.* FROM accounts a INNER JOIN friends fr ON (a.id = fr.friend_id) WHERE fr.id = ?");
$q -> execute(array($details['id']));
Now this is basically where the id matches in the friends table, pull the friends id and all the relevant data with it.
I am trying to implement a friends online page as well, how would I also test to see if a column in accounts for the friend_id matches a certain criterion?
This is how I pull all the users that are online...
$online_users = time() - 900;
$q = $dbc -> prepare("SELECT * FROM accounts WHERE last_active > ? && id != ? ORDER BY id");
$q -> execute(array($online_users, $details['id']));

SELECT a.*
FROM accounts AS a
JOIN friends AS f ON (a.id = f.friend_id)
WHERE f.id = ?
AND a.last_active > ?
ORDER BY id
You don't need to repeat the condition on a.id since the join enforces it.

Related

How to view data based on user in codeigniter

I want to view data from mysql in codeigniter based on user who is logged in
but I got an error "A Database Error Occurred". I think I wrote the wrong code
t.USER = $this->session->userdata('user_id');
Here's the code:
function get_rekomen()
{
$query = $this->db->query("SELECT
c.*,
t.produk_id,
t.id_transdet,
t.kategori_id,
t.total_qty,
t.USER
FROM
transaksi_detail AS t
LEFT JOIN
(
SELECT
g.id_produk,
p.slug_produk,
p.foto,
p.foto_type,
p.harga_diskon,
p.diskon,
p.harga_normal,
p.judul_produk,
g.kat_id,
k.judul_kategori
FROM
(
SELECT
MAX(m.id_produk) AS id_produk,
m.kat_id
FROM
produk AS m
GROUP BY
m.kat_id
)
AS g
INNER JOIN
produk AS p
ON p.id_produk = g.id_produk
LEFT JOIN
kategori AS k
ON k.id_kategori = g.kat_id
)
AS c
ON c.kat_id = t.kategori_id
WHERE
t.USER = $ this -> session -> userdata('user_id');
<<// i think here's the problem
ORDER BY
total_qty DESC limit 1")->result();
return $query;
}
and the question is what is the correct code?
Here's one solution, but first make sure on your controller the $this->load->library('session'); is loaded or you can just add in on autoload.php.
Also you must add parameter to your model that will handle the user_id in session, so for example here's your model looks like:
function get_rekomen($user_id) { ...your query here... }
Then on condition using the user_id will be
t.USER = $user_id;
So on your controller, you can call your model like:
$user_id = $this->session->userdata('user_id');
$this->ModelClass->get_rekomen($user_id);
Additional: On your login phase, if the user success from logging in, the you must set the user data on session such as this $this->session->set_userdata('user_data', $session_data);
Hope this helps!
Maybe you can use this. You need to define $user_id first before adding them to WHERE statement...
$user_id = $this->session->userdata('user_id');
$sql = "SELECT c.*, t.produk_id, t.id_transdet, t.kategori_id, t.total_qty, t.USER
FROM transaksi_detail AS t
LEFT JOIN(SELECT g.id_produk, p.slug_produk, p.foto, p.foto_type, p.harga_diskon, p.diskon, p.harga_normal, p.judul_produk, g.kat_id, k.judul_kategori
FROM(SELECT MAX(m.id_produk) AS id_produk, m.kat_id
FROM produk AS m
GROUP BY m.kat_id)
AS g
INNER JOIN produk AS p ON p.id_produk = g.id_produk
LEFT JOIN kategori AS k ON k.id_kategori = g.kat_id)
AS c ON c.kat_id = t.kategori_id
WHERE t.USER = '$user_id'
ORDER BY total_qty DESC limit 1";
$query = $this->db->query($sql);
return $query->result();
Hope this can help you...

How to optimise query

This query returns all friends of logged in user, which is present in "network" table in below query. This maps frd_id and mem_id from these two tables.
I have optimized this query. but still it is taking time to get result.
Please suggest me optimized query for the same.
SELECT m.mem_id,m.profilenam,m.gender,m.photo_thumb,m.profile_type,n.frd_id as mem_id
FROM `network` n
left join members m on(n.frd_id=m.mem_id)
where ((n.frd_id = m.mem_id and n.mem_id=$uid)
or (n.mem_id = m.mem_id and n.frd_id=$uid))
AND m.ban='n'
AND m.deleted<>'Y'
and profilenam like '%'
Try this:
SELECT m.mem_id,m.profilenam,m.gender,m.photo_thumb,m.profile_type,m.mem_id
FROM `network` n
JOIN members m ON n.frd_id = m.mem_id
AND ( n.mem_id = $uid
OR ( n.mem_id = m.mem_id
AND n.frd_id = $uid
)
)
WHERE m.profilenam IS NOT NULL
AND m.ban = 'n'
AND m.deleted <> 'Y';

using join a table to itself and join another table

I have two tables like below pictures :
users table :
offer_comments
offer_comments table stores comments and answer to comments.
by using below function I can get comments and answer to comments depending on $id.
function getCommentsAnItem($id){
mysql_query("SET CHARACTER SET utf8");
$result_comments = mysql_query("select e.comment as comment,m.comment as answer_to_comment
from offer_comments e
inner join offer_comments m on e.id = m.quet
where e.offer_id=$id and e.confirm=1");
$comments = array();
while($a_comment=mysql_fetch_object($result_comments)){
$comment = array(
'comment'=>$a_comment->comment,
'answer'=>$a_comment->answer_to_comment
);
array_push($comments,$comment);
}
return $comments ;
}
How do I can get name and family from users table depending on user_id in offer_comments table ?
updated:
admin is where user_id equal = 1 .
user_id 14690 is a user and leaves a comment and admin answer to him.
in the users table :
I would like to get an array of comments and answer to comments depending on $id :
"comment=>how a u ?","answer=> I am fine","comment.name=>name","comment.family=>family"
Join your user table with your current query with offer_comments aliased as m so it will show the name and family of user who belongs to m.comment or the one who added m.comment,if you want to show the user of offer_comments aliased as e then join on e.user_id
SELECT
e.comment AS `comment`,
m.comment AS answer_to_comment,
u.name,
u.family
FROM
offer_comments e
INNER JOIN offer_comments m
ON e.id = m.quet
INNER JOIN users s
ON s.id = m.user_id
WHERE e.offer_id = $id
AND e.confirm = 1

mySQL reference correlation in a subquery with join

I'm working on a small social network service.
Very classically, I have 3 tables :
- table "circles_users" : all users that belong to the same "circle"
- table "friends" : friendship relation between users
- table "checkin" : is a user "checkin" somewhere or not
Here the structure of the database : http://sqlfiddle.com/#!2/27888/1
I would like to ask my database to give me :
all users from a specific "circle" with for each of them :
- the number of friends this user has in common with user id = 3
- if this user is checkin or not
Here what I'm trying to do :
SELECT a.uid,
(
SELECT COUNT(*)
FROM (SELECT IF (uid1 = 3, uid2, uid1) AS cf FROM friends WHERE (friends.uid1 = 3 OR friends.uid2 = 3 )) as b
JOIN friends ON ((friends.uid1 = b.cf AND friends.uid2 = a.uid) OR (friends.uid1 = a.uid AND friends.uid2 = b.cf))
) as common_friends,
checkin.status as checkin_status
FROM
(SELECT circles_users.uid FROM circles_users WHERE circles_users.circlename = 'circle_A') as a
LEFT JOIN checkin ON checkin.uid = a.uid
I get this error message : Unknown column 'a.uid' in 'on clause'
It has been now 2 days that I'm trying to fix this unsuccessfully.
It seems that it is not possible to reference correlation name in my subquery.
For instance, if I replace a.uid in the subquery by a specific uid (for instance let's say '4'), I don't get any error. But of course, the result is false...
Is there someone who could help me ?
That would be very nice :)
OTHER OPTION TO FOLLOW ?
Another option would be to pass the "common_friends" subquery as a join.
I tried to do something like this :
SELECT a.uid,
c.cnt as common_friends,
checkin.status as checkin_status
FROM
(SELECT circles_users.uid as uid FROM circles_users WHERE circles_users.circlename = 'circle_A') as a
LEFT JOIN
(
SELECT DISTINCT COUNT(*) as cnt
FROM (SELECT IF (uid1 = 3, uid2, uid1) AS cf FROM friends WHERE (friends.uid1 = 3 OR friends.uid2 = 3 )) as b
JOIN friends ON ((friends.uid1 = b.cf AND friends.uid2 = a.uid) OR (friends.uid1 = a.uid AND friends.uid2 = b.cf))
) as c ON 1=1
LEFT JOIN checkin ON checkin.uid = a.uid
But again : I get this error message : Unknown column 'a.uid' in 'on clause'Anyway, do you think this version would be easier to handle and would open new possibilities to resolve my problem ?
If you want to play with my queries : (thanks to #zundarz)
http://sqlfiddle.com/#!2/27888/1
Rewrote a query based on the info you give and what you are looking for.
SELECT cu.uid, COUNT(f.uid1) common_friends, c.status
FROM circles_users cu
LEFT JOIN friends f
ON (f.uid1 = cu.uid OR f.uid2 = cu.uid)
AND f.status = "on"
AND IF (f.uid1 = cu.uid, f.uid2, f.uid1) IN (
SELECT IF (uid1 = 3, uid2, uid1)
FROM friends
WHERE status = "on"
AND (friends.uid1 = 3 OR friends.uid2 = 3)
)
LEFT JOIN checkin c
ON c.uid = cu.uid AND c.status = "on"
WHERE cu.circlename = "circle_A"
GROUP BY cu.uid
Example sqlFiddle

Duplicate column name 'user_id' problem

I'm having a problem trying to count the number of user records according to the user's id, however I'm using a subquery to join 2 tables that one has a count parameter but I get an error saying duplicate column name 'user_id.
The query:
$sql = "SELECT loc.location_id,
COUNT(loc.location_id) AS total_records
FROM locations loc
LEFT JOIN
(
SELECT usr.*,
loc.*
FROM
(
members usr
INNER JOIN locations loc
)
WHERE usr.user_id = " . $user_id . "
AND usr.account_disabled = 0
ORDER BY loc.submit_date DESC
) usr ON (loc.user_id = usr.user_id)";
All I need it is to return the user's info and the total_records count done by the COUNT function.
Cheers.
EDIT:
This is what I get returned for this SQL:
SELECT loc.location_id,
loc.street_name,
loc.city,
loc.state,
loc.county,
loc.country,
usr.user_id,
usr.username,
COUNT(loc.location_id) AS total_records
FROM locations loc
INNER JOIN members usr ON (loc.user_id = usr.user_id)
WHERE loc.user_id = $user_id
AND usr.account_disabled = 0
GROUP BY loc.location_id
It's not exactly clear why you've got the derived resultset or the LEFT JOIN. Try this:
SELECT loc.location_id,
COUNT(loc.location_id) AS total_records
FROM LOCATIONS_TABLE loc
INNER JOIN MEMBERS_TABLE usr
ON (loc.user_id = usr.user_id)
WHERE loc.user_id = $user_id
AND usr.account_disabled = 0
GROUP BY loc.location_id
I think the problem is this part:
SELECT usr.*,
loc.*
Both tables have a user_id