hello all i am having this query in my webpage
$otherupdates=mysqli_query
($conn,"
SELECT f.sender,f.receiver,f.field,m.name
FROM friend f,members m
WHERE ((f.sender IN ($variable) OR f.receiver IN ($variable))
AND ( f.field='friends' || f.field='fan')
AND ( f.date > '$adatevariable' AND f.sender=m.id))
ORDER BY date DESC LIMIT 16"
);
$variable="'1','2','3'......"; // not important
$adatevariable=date('d', strtotime($today . ' - 2 day'));// not imp
what this query does is, fetches all the rows which matches the where clause and also fetches the name of sender (f.sender=m.id) but i want the name of receiver too by this query only i do not need another query..
is this possible please help
If you change your query to be:
select
f.sender,
f.receiver,
f.field,
senders.name AS sender_name,
recievers.name AS recievers_name
from
friend f
INNER JOIN members senders ON f.sender=senders.id
INNER JOIN members recievers ON f.receiver = recievers.id
where
(f.sender IN ($variable) or f.receiver IN ($variable))
and f.field IN ('friends', 'fan')
and f.date > '$adatevariable'
order by
date desc
limit 16
What this does is allow you to access the members table twice, once as senders and again as recievers. By joining these to your friend table on the sender and reciever fields, senders will have all the information of the sender and recievers will have all the information on the reciever.
Related
So I created this query
SELECT a.email
, a.password
, a.server
, a.status
, a.step
, b.*
FROM mail a
JOIN automation_logs b
ON b.accountid = a.accountid
WHERE a.status <0
ORDER
BY b.created DESC;
What it's used for is essentially I'm trying to get debug information from our log table for email accounts that are errored out on our api. The automation_logs table essentially is text dump of error messages that were produced by our API.
This query gives me what I want but gives me too much. I only want the last five most recent (read: created field is a timestamp) error messages for any of the accounts as some of these accounts have existed for years and old errors have been fixed and aren't necessary to know what's broken and just pad the results.
Is this possible with a single query?
Following the advice listed here: Thank you Marshal Tigerus
I was able to get it to work with the following sql:
SET #currcount = NULL, #currvalue = NULL;
SELECT a.email,a.password,a.serverid,a.status,a.step,b.message,b.created FROM mail as a JOIN (
SELECT * FROM (
SELECT
*,
#currcount := IF(#currvalue = accountid, #currcount + 1, 1) AS num,
#currvalue := accountid AS cur_id
FROM automation_logs
WHERE message NOT LIKE ""
ORDER BY accountid, created DESC
) as limitedresults WHERE num <= 5
) as b ON a.accountid = b.accountid WHERE a.status < 0 ORDER BY b.created DESC
My table for message inbox concept email is a primary in the table. I want to get the last message which is sent by particular email.
tbl_msg:
id
email
msg
Example Data:
Id email msg
1 xyz#gmail.com This is test
2 abc#gmail.com All is well
3 xyz#gmail.com This is test2
I want to get the last appearance of each email and msg
Id email msg
2 abc#gmail.com All is well
3 xyz#gmail.com This is test2
What I tried:
SELECT cnote.`id`,cnote.`email`,cnote.`msg` FROM `tbl_msg` cnote inner join (select distinct email,id from client_com group by email) as note
on cnote.id=note.id
Guide me if I wrong
Use This query:
SELECT m1.* FROM tbl_msgs m1 LEFT JOIN tbl_msgs m2 ON (m1.email = m2.email AND m1.id < m2.id) WHERE m2.id IS NULL;
This will join with the same table and with condition m1.id < m2.id , will get the latest one.
Another option is using subquery:
SELECT * FROM tbl_msgs WHERE id IN (SELECT MAX(id) FROM tbl_msgs GROUP BY email);
To get the latest messsage for each email address in the table you do not need a JOIN, you just need to ORDER and GROUP BY:
SELECT `id`, `email`, `msg`
FROM `tbl_msg`
GROUP BY `email`
ORDER BY `id` DESC
You can use this query:
SELECT id, email, msg FROM you_table
GROUP BY email
ORDER BY id DESC
With this one you will have only 1 row per email, and you'll have the last because is ordered by id DESC.
If you are running a PDO connection (The way I know to do it, not sure if there is a MySQLi way)
$theLastIdGiven = $handlerDbConnection->lastInsertId();
Or if you want to run it through a query, and get the last result, just add ORDER BY id DESC LIMIT 0, 1 and that will order the data by id in a descending form then get the first bit of data :)
Hope this helped you!
SELECT ID, email, Msg FROM tbl_msg WHERE ID IN (
(SELECT MAX(ID) FROM tbl_msg GROUP BY email))
I have 4 tables:
Table 1: Users
id
username
Table 2: Acts
act_id
act
user_id
act_score
act_date
Table 3: Votes
vote_id
act_id
user_voter_id
score_given
date_voted
Table 4: Comments
comment_id
comment
commenter_id
act_commented
date_commented
I want to show the contents of Acts Votes and Comments, based on User ID, combined in a list sorted in date order. Similar idea to Facebook's NewsFeed.
Sample output:
05-02-2014 10:00 Comment: "That's funny"
04-02-2014 12:30 Act Posted: "This is what I did"
04-02-2014 11:00 Comment: "Rubbish"
03-02-2014 21:00 Comment: "Looks green to me"
02-02-2014 09:00 Voted: +10 "Beat my personal best" by Cindy
01-02-2014 14:25 Act Posted: "Finally finished this darn website!"
I have tried to go down the create VIEW route to add all the required info to a table but
it was the wrong path. Now I'm not sure what to do!
Use UNION to combine separate queries. For example, to get the 10 most recent events across the three tables:
(
-- my acts
SELECT a.act_date timestamp,
'Act Posted' type,
a.act description,
u.username
FROM Acts a
JOIN Users u ON u.id = a.user_id
WHERE a.user_id = ?
ORDER BY a.act_date DESC
LIMIT 10
) UNION ALL (
-- votes on my acts
SELECT v.date_voted,
CONCAT('Voted ', v.score_given),
a.act,
u.username
FROM Votes v
JOIN Acts a USING (act_id)
JOIN Users u ON u.id = v.user_voter_id
WHERE a.user_id = ?
ORDER BY v.date_voted DESC
LIMIT 10
) UNION ALL (
-- comments on my acts
SELECT c.date_commented,
'Comment',
c.comment,
u.username
FROM Comments c
JOIN Acts a ON a.act_id = c.act_commented
JOIN Users u ON u.id = c.commenter_id
WHERE a.user_id = ?
ORDER BY c.date_commented DESC
LIMIT 10
)
ORDER BY timestamp DESC
LIMIT 10
first of all make id as a foreign key and use it in rest of the 3 tables while inserting data into those 3 tables.
like for Acts table,table structure should be like below.
Table 2: Acts
id //this is user id which is stored in the session while login.
act_id
act
user_id
act_score
act_date
The another thing to do is manage session for each and every user while he/she logged in.
Store user_id in the session for the further use like below.
session_start();
$_SESSION['user_id']=$_POST['ID'];
Then,fire select query for the particular table.I give you example of select query.
$sql="select * from Acts where id='".$_SESSION['id']."' ORDER BY act_date DESC";
$query=mysql_query($sql) or die("query failed");
Now, you will get result of Acts of particular user order by date.Then print it wherever you want.
i have two tables in my db .. one is Messages and the other is Contacts... both tables contain the mobile_number field.. in Contacts table there is no duplicate numbers ... but in Messages tables there are several duplicate numbers in mobileNo field...what i am doing is write now i am selecting the distinct mobile numbers from the Messages tables and then i am comparring the distinct numbers from the contacts table ... so if the messages_mobileNo is found on the contacts table then give me the contact name against the number otherwise messages_mobileNo ... so the problem is distinct not working .. i am not able to get the distinct numbers from the Messages table ... it is showing me the duplicate numbers
here is my query
SELECT DISTINCT Message.mobileNo,
Contact.mobileNo,
Contact.workNo,
Contact.homeNo,
Contact.other,
Contact.name,
Message.body,
Message.idTextMessage
FROM cakephp_db.textmessage AS Message
LEFT JOIN cakephp_db.contacts AS Contact ON (Message.user_id = Contact.user_id
AND ((Message.mobileNo = Contact.mobileNo)
OR (Message.mobileNo = Contact.workNo)
OR (Message.mobileNo = Contact.homeNo)
OR (Message.mobileNo = Contact.other)))
WHERE Message.User_id = 23
ORDER BY Message.idTextMessage DESC LIMIT 6
So your trying to get the last 6 messages of a person if I'm right?
SELECT Message.mobileNo,
Contact.mobileNo,
Contact.workNo,
Contact.homeNo,
Contact.other,
Contact.name,
Message.body,
Message.idTextMessage
FROM cakephp_db.textmessage AS Message
LEFT JOIN cakephp_db.contacts AS Contact ON Message.user_id = Contact.user_id
AND Message.mobileNo IN (Contact.mobileNo, Contact.workNo, Contact.homeNo, Contact.other)
WHERE Message.User_id = 23
GROUP BY Message.mobileNo
ORDER BY Message.idTextMessage DESC LIMIT 6
add a GROUP BY Message.mobileNo before your ORDER BY
If you are using MySQL SELECT DISTINCT with an ORDER BY added to it, you will have to create a temporary table where it can store its results. Here is a link offering more help:
MySQL DISTINCT Optimization
I currently have a MySQL SELECT statement that pulls information from two tables to display a "Sent Messages" field for private messaging.
I'd like to know how I can do add a COUNT to my query to count the number of "receivers" in one thread.
Here's the basic gist of my table structure, (NOTE: the relational tie between the two tables is the 'message-id' in pm-info and the "id" in pm_data):
pm_info:
id message_id receiver_id is_read read_date
pm_data:
id date_sent title sender_id thread_id content
Here's my SELECT Statement:
SELECT pm_info.is_read, group_concat(DISTINCT receiver.usrFirst) as receiver_name,
pm_data.date_sent, pm_data.title, pm_data.thread_id, pm_data.id as data_id,
MAX(date_sent) AS thread_max_date_sent
FROM pm_info
INNER JOIN pm_data ON pm_info.message_id = pm_data.id
INNER JOIN tblUsers AS receiver ON pm_info.receiver_id = receiver.usrID
WHERE pm_data.sender_id = '$usrID'
GROUP BY pm_data.thread_id
ORDER BY thread_max_date_sent DESC
And it ouputs the recipients like this:
Message 1 - Recipients: John, David, Steve - thread_id = 1234
Message 2 - Recipients: Bill, David, John, Ed, Steve - thread_id = 1345
Basically, what I'd like to do is have the option to COUNT the recipients, so in the example above, "Message 1" would display three (3) recipients, and "Message 2" would display five (5) recipients.
This way, if I have a thread/message that was sent to 30 users, not all thirty names will be printed out.
Thanks!
Have you tried just replacing GROUP_CONCAT with COUNT? Like this:
COUNT(DISTINCT receiver.usrFirst) as receiver_count
Or better, use pm_info.receiver_id as in (which could potentially let you eliminate one of your joins):
COUNT(DISTINCT pm_info.receiver_id) as receiver_count
You could use a subquery to select up to 3 recipients per message, and then another subquery to concatenate their names:
select
( select group_concat(usrFirst separator ', ')
from tblUsers
where usrId in (
select usrId
from tblUsers
where usrId = pm_info.receiver_id
limit 3
)
) as receiver_name
from pm_info
....
You could move the count and group_concat into a concat statement.
... group_concat(DISTINCT receiver.usrFirst) as receiver_name ...
becomes
... concat('messages:', count(distinct receiver.usrFirst),'(',group_concat(DISTINCT receiver.usrFirst),')') as receiver_name ...