why does this SQL Code not run?
user_chats
id | user_id | to_user_id | ad_id | timestamp
----------------+---------+------------+---------+-----------
1 | 1 | 6 | 13 | 1513516133
user_messages
id | chat_id | text | user_id | timestamp
----------------+---------+------------+---------+-----------
1 | 1 | Hello | 1 | 1513516133
2 | 1 | Hi! | 6 | 1513516754
I want to get the Chats and order them by user_messages.timestamp.
My SQL Code is:
SELECT user_chats.id,
user_chats.timestamp,
ad_id,
title,
user_chats.user_id
FROM user_chats
INNER JOIN ads
ON ads.id = ad_id
WHERE user_chats.user_id = "1"
OR user_chats.to_user_id = "1"
ORDER BY (SELECT id
FROM user_messages
WHERE chat_id = user_chats.id
ORDER BY user_messages.id DESC)
The issue is that you've used a subquery in your Order By clause: as this returns multiple results for each record in the main query it cannot be used to order the results of the main query.
I think you're trying to order the results by the latest message in each chat, but simply joining the user_messages table will mean you'll get duplicates (each chat being returned once per message). You can get around this by joining to an inline view:
SELECT DISTINCT user_chats.id,
user_chats.timestamp,
ad_id,
title,
user_chats.user_id
FROM user_chats
INNER JOIN ads
ON ads.id = ad_id
LEFT JOIN
--in line view aliased 'UM' returns one row per chat_id in user_messages, with the last timestamp for that ID
(SELECT max(timestamp) LastMessage,
chat_id
FROM user_messages
GROUP BY chat_id) um
ON um.chat_id = user_chats.id
WHERE user_chats.user_id = 1
OR user_chats.to_user_id = 1
ORDER BY um.LastMessage desc
Related
I've a following query to select data from a table (chat) in a chat system:
SELECT * FROM (SELECT * FROM chat WHERE id_chat = '$chat_id' ORDER BY id DESC LIMIT 10) S
WHERE id_chat = '$chat_id'
ORDER BY id ASC
LIMIT 10
In this table (chat), there is a user column where it is the user id that sent the message.
I would, from the id_from of the user who sent the message, get back data that user (users table).
Table chat:
id | id_chat | id_from | id_to | message | date
1 | 23 | 1 | 2 | hello! | 01-12-2016
Table users:
id | name | photo
1 | John | pic.png
2 | Nick | hey.jpg
What better way to do it using the above query? LEFT JOIN? INNER JOIN? And, how do?
In my page I have a tab named Recent activity, In which I have to display the two different types of actions
Recently added choices
Recently voted choices
The table stucture for je_addchoice
je_addpoll table
poll_id | user_id | poll_name | category_id | start_date | end_date
1 | 20 |Naturalflrs| 18 | 2012-12-03 | 2095-12-25
je_addchoice table
choice_id | poll_id | choice_creator_id | choice_name | choice_image | description | ctime
1 | 1 | 20 | Greenish | forest.jpg | forest |135453
je_user_vote table
vote_id | user_id | poll_id | choice_id | datetime_voted | user_type
12 | 31 | 1 | 1 |12-12-2606:23:17| normal
Already I have the result page displays as shown below
The above result is displayed using the query
$result=mysql_query("SELECT * FROM je_addchoice, je_addpoll where je_addpoll.start_date <= '$check_date' AND je_addpoll.end_date >='$check_date' AND je_addpoll.poll_id=je_addchoice.poll_id order by je_addchoice.choicecreationtime desc");
The two tables
1) je_addpoll (Main table for polls)
2) je_addchoice (adding choices for the polls)
But what I want to do here is If any user votes for the poll, It will store into
je_user_vote table as shown above.
I want to display the recently voted choices in the same tab
Try this
use desc order for datetime_voted just before je_addchoice.choicecreationtime desc
like this.
$result=mysql_query("SELECT * FROM (SELECT P.poll_id,P.user_id,P.poll_name,P.category_id,P.start_date,P.end_date,C.choice_id,C.choice_creator_id,C.choice_name,C.choice_image,C.description,C.ctime FROM je_addchoice C, je_addpoll P where P.start_date <= '$check_date' AND P.end_date >='$check_date' AND P.poll_id=C.poll_id order by C.choicecreationtime desc) N,je_user_vote U WHERE U.poll_id=N.poll_id order by U.datetime_voted desc,N.choicecreationtime desc");
OR
$result=mysql_query("SELECT N.poll_id,N.user_id,N.poll_name,N.category_id,N.start_date,N.end_date,N.choice_id,N.choice_creator_id,N.choice_name,N.choice_image,N.description,N.ctime FROM (SELECT P.poll_id,P.user_id,P.poll_name,P.category_id,P.start_date,P.end_date,C.choice_id,C.choice_creator_id,C.choice_name,C.choice_image,C.description,C.ctime FROM je_addchoice C, je_addpoll P where P.start_date <= '$check_date' AND P.end_date >='$check_date' AND P.poll_id=C.poll_id order by C.choicecreationtime desc) N,je_user_vote U WHERE U.poll_id=N.poll_id order by U.datetime_voted desc,N.choicecreationtime desc");
this one been puzzling me for a couple of searching hours.
So I have a campaign table and a vendor Table. The vendor might have several campaigns.
I want to select all campaigns if the vendor has enough credits.
Problem is I don't know how many campaigns are going to be selected from the same vendor which means that the vendor might still have credits for two campaigns but not for the rest of them.
Example
tblvendors
+---------+------------+---------------+
|vendorId | vendorName | vendorCredits |
+---------+------------+---------------+
| 1 | a | 5 |
| 2 | b | 100 |
+---------+------------+---------------+
tblproducts
+-----------+---------------+------------+
| productId | productName | vendorId |
+-----------+---------------+------------+
| 1 | c | 1 |
| 2 | e | 2 |
| 3 | f | 1 |
| 4 | g | 1 |
| 5 | h | 1 |
+-----------+---------------+------------+
tblcampaigns
+------------+---------------+------------+
| campaignId | productId | vendorId |
+------------+---------------+------------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 1 |
| 4 | 4 | 1 |
| 5 | 5 | 1 |
+------------+---------------+------------+
Now considering that everytime a row is selected the vendor looses 2 credits since vendor 'a' only has 5 credits left only campaigns 1 2 and 3 should be returned.
My current Query is this:
SET #maxCampaignId = (SELECT MAX(campaignId) FROM tblCampaigns);
SELECT
#maxCampaignId,
t0.campaignId,
t0.productId,
productName,
productDescription,
productImage,
(CASE WHEN campaignId > (SELECT configValue FROM tblconfiguration WHERE configKey = 'lastHomeCampaignId')
THEN campaignId ELSE campaignId + #maxCampaignId END) AS orderField
FROM tblcampaigns AS t0
INNER JOIN tblproducts AS t1 ON t0.productId = t1.productId
INNER JOIN tblvendors AS t2 ON t1.vendorId = t2.vendorId
WHERE
campaignType = 'homeFeature' AND
t0.isActive = 1 AND
t2.vendorCredits > (SELECT configValue FROM tblconfiguration WHERE configKey = 'campaignHomeFeatureCost' LIMIT 1)
ORDER BY orderField ASC
LIMIT 4
The problem as you can see is int the line that compares the vendorCredits. Obviously as is the query selects more campaigns than the vendor can afford.
I wanted to avoid doing this in PHP as I think it should be possible to do this straight out of the database.
Check this post, it may help - group by and having clauses. I'll try to do some test later
Using COUNT(*) in the WHERE clause
UPDATE:
select t2.vendorId, vendorCredits from tblcampaigns AS t0 JOIN tblproducts AS t1 ON t0.productId = t1.productId JOIN tblvendors AS t2 ON t1.vendorId = t2.vendorId group by t2.vendorId having t2.vendorCredits = count(t2.vendorId)
If I correctly understood the question: This query will select all vendors having more campains than credits.
Ok found it.
Thanks to this post: How do I limit the number of rows per field value in SQL?
What I did was Selecting the rows I wanted in the order I wanted as a subquery and its respective row number so that I could reorder it back in the end.
Then I made a second subquery ordered by the vendorId so that I could count the number of times it turned up and returning the row_count to the main query.
Finally in the main query I reordered it back to the row number in the deepest subquery but now I have the value I wanted to compare which is the value of credits per row * the current row number for a particular vendor.
Anyways maybe the code is cleared and here it goes:
SET #creditsCost = (SELECT configValue FROM tblconfiguration WHERE configKey = 'campaignHomeFeatureCost' LIMIT 1);
SET #maxCampaignId = (SELECT MAX(campaignId) FROM tblCampaigns);
SET #curRow = 0;
SELECT * FROM
(
SELECT *,
#num := if(#first_column = vendorId, #num:= #num + 1, 1) as row_num,
#first_column:=vendorId as c
FROM
(SELECT
#curRow := #curRow + 1 AS row_number,
#maxCampaignId,
t0.campaignId,
t0.productId,
t2.vendorId,
t2.vendorCredits,
productName,
productDescription,
productImage,
(CASE WHEN campaignId > (SELECT configValue FROM tblconfiguration WHERE configKey = 'lastHomeCampaignId')
THEN campaignId ELSE campaignId + #maxCampaignId END) AS orderField
FROM tblcampaigns AS t0
INNER JOIN tblproducts AS t1 ON t0.productId = t1.productId
INNER JOIN tblvendors AS t2 ON t1.vendorId = t2.vendorId
WHERE
campaignType = 'homeFeature' AND
t0.isActive = 1
ORDER BY orderField ASC) AS filteredCampaigns
ORDER BY vendorId
) AS creditAllowedCampaigns
WHERE
row_num * #creditsCost <= vendorCredits
ORDER BY row_number
Anyhow I still appreciate Who took the time to answer and try to help, and will be listening to future comments since I think this is not the best way performance wise.
What I would like to do is retrieve all data from a table, and order them by the number of games the user played in a specific category. Is there any way I can use some sort of "COUNT WHERE" sql statement?
here's what i have so far. it will only return the user if they have played a game in the "fps" category, but I want it to show all users in descending order even if they have not played an fps game. please excuse my crappy tables
SELECT user_data.user, COUNT(played_games.game_cat) as 'count'
FROM user_data, played_games
WHERE user_data.user_id = played_games.user_id and played_games.game_cat = 'fps'
GROUP BY user_data.user_id
ORDER BY 'count' DESC;
user_data table
user_id | user
1 | jeff
2 | herb
3 | dug
played_games table
id | user_id | game | game_cat
1 | 2 | kill | fps
2 | 1 | shoot| fps
3 | 2 | COD | fps
4 | 3 | dogs | cas
You need a LEFT OUTER JOIN to get the records even if a corresponding record does not exist in the other table.
SELECT user, coalesce(count(game_cat), 0) as count
FROM user_data LEFT OUTER JOIN played_games
ON user_data.user_id = played_games.user_id AND played_games.game_cat='fps'
GROUP BY user_data.user_id
ORDER BY count desc;
Gives the following result on my screen
+------+-------+
| user | count |
+------+-------+
| herb | 2 |
| jeff | 1 |
| dug | 0 |
+------+-------+
This is how I'd do it. No subquery, no COALESCE, no COUNTIF junk.
SELECT `users`.`user`, COUNT(`played_games`.id) AS `c`
FROM `users`
LEFT OUTER JOIN `played_games` ON
`users`.`user_id` = `played_games`.`user_id`
AND `played_games`.`game_cat` = "fps"
GROUP BY `users`.`user_id`
ORDER BY `c` DESC, `user` ASC
SQLFiddle (not sure if you can link them like this...)
Try this:
SELECT ud.user, coalesce(sum(pg.game_cat = 'fps'), 0) Total
FROM user_data ud
LEFT JOIN played_games pg ON ud.user_id = pg.user_id
GROUP BY ud.user_id
ORDER BY Total DESC
This will show all users and the amount of times they've played a game with category 'fps'.
The coalesce one is promising, but doesn't work for me, sigh~ I just found NULLIF is a good way to solve this problem. Remember to use LEFT JOIN
COUNT( NULLIF(TABLE.ATTR, 1) ) AS total_count
The TABLE.ATTR is some field that can be NULL, here is an example:
SELECT Posts.*, COUNT( NULLIF(Comments.user_email, 1) ) as comment_num
FROM (`Posts`)
LEFT OUTER JOIN `Comments` ON `Comments`.`post_id` = `Posts`.`id`
GROUP BY `Posts`.`id`
LIMIT 5
Got the idea from http://www.bennadel.com/blog/579-SQL-COUNT-NULLIF-Is-Totally-Awesome.htm
Below query the all game category with user id and order by count
select * from (SELECT user_data.user, COUNT(played_games.game_cat) as 'count'
FROM user_data, played_games
WHERE user_data.user_id = played_games.user_id(+) GROUP BY user_data.user_id)
order by count desc
I have this table: I want to search by UID
ID | VID | UID
1 | 1 | 5
1 | 1 | 6
1 | 2 | 6
2 | 3 | 5
2 | 3 | 6
2 | 4 | 6
I want to end up with this result:
ID | VID | UID
1 | 2 | 6
2 | 4 | 6
In other words, only select the entries where the VID is MAX of the UID but keeping in min NID could differ. Something like this I suppose:
select * from TABLE where uid = 6 and max(vid)
???
But this doesn't work?
One way is to order by the value in descending order (so the max is at the top), then just select the first result.
SELECT t.ID,
t.VID,
t.UID
FROM table t
WHERE t.ID = 1
ORDER BY t.VID DESC
LIMIT 1
Or do you mean you want all rows where t.VID is the highest value? In which case you could do something like this,
SELECT t.ID,
t.VID,
t.UID
FROM table t
WHERE t.ID = 1
AND t.VID = (SELECT MAX(VID) FROM table);
EDIT: Based on the edit to your question, it looks like you just want the max VID value for each ID? If I'm understanding you correctly, then this should give you what you need.
SELECT t.ID,
max(t.VID) as VID,
t.UID
FROM table t
WHERE t.UID = 6
GROUP BY t.ID
You need to have a subquery. This should work:
select * from TABLE where ID='1' AND VID=(select max(VID) from TABLE)
I expect your real-life example is more complicated (at least has more data).
This query will give you the row you want.
SELECT id,vid, uid
FROM TABLE
where id = 1
and vid in (select max(vid) from TABLE where id = 1)