Using Order By with Union - SQL Statement - php

I have a database with direct messages from one user to another.
Table name: dm
id int(11) Primary Key
to: varchar
from: varchar
message: varchar
I have a SQL Statement that selects the distinct values from the to and from column as if they were one column. ($username is a session variable)
"SELECT DISTINCT from
FROM dm
WHERE to = '$username'
UNION
SELECT DISTINCT to
FROM dm
WHERE from = '$username'
";
I am checking to see if this user has received or sent any messages basically. I want to ORDER BY id of dm. How can I change my code so I get the same results and it orders by id DESC? If I simply enter ORDER BY like so, I get an error because I didn't select it... Thank you so much for the help
"SELECT DISTINCT from
FROM dm
WHERE to = '$username'
UNION
SELECT DISTINCT to
FROM dm
WHERE from = '$username'
ORDER BY id DESC
";

If I got exactly what you wanted to do you should keep things separate:
1st step: your original code, plus the user ID added to the dataset
CREATE TABLE new_table_name AS
SELECT DISTINCT ID, from
FROM dm
WHERE to = '$username'
UNION
SELECT DISTINCT ID, to
FROM dm
WHERE from = '$username';
2nd step: order by ID
CREATE TABLE ordered_table AS
SELECT *
FROM new_table_name
ORDER BY ID DESC;

Related

SQL get common values in a database

I'm using Sqlsrv and I need to find common values within the same table using PHP. There are two main columns, user_id and bssid.
Using a selected $user_id, I need to find all common "bssid" values and return a set of users which contain these values (this is if another user_id has one or more bssid the same).
This is my query string so far. My logic doesn't work.
$sql = "SELECT A.* FROM AccessPoints A INNER JOIN (SELECT bssid, user_id
FROM AccessPoints WHERE user_id='$userID'
GROUP BY bssid, user_id
HAVING COUNT(*) >= 1) B
ON A.bssid = B.bssidB.user_id = A.user_id";
The database schema is as such:
A sample of the dataset can be seen as such, and contains the data from two users:
I simply want to query a user_id and return all other user_ids which have similar bssids
If you want all the user_id including the the one you are searching on then:
SELECT user_id
FROM AccessPoints
WHERE bssid IN(SELECT bssid
FROM AccessPoints)
WHERE user_id = '$userID')
If you want to exclude the one you are searching from the output then:
SELECT user_id
FROM AccessPoints
WHERE bssid IN(SELECT bssid
FROM AccessPoints)
WHERE user_id = '$userID')
AND user_id != '$userID'

PHP MySQL - Select the ID with the highest number

I have a table where multiple records can be stored by the same user on a daily basis.
So right now I'm doing this:
SELECT * FROM `mytable` WHERE user_id = '$userid'
Now, what I need to do is to select the latest entry available by that user, something like:
The table has an ID field which is auto increment so, I was thinking something like:
SELECT * FROM `stats` WHERE user_id = '$userid' WHERE ID <- Is the latest..
How can I do that and select Where ID is the latest ?
How about
SELECT *
FROM `stats`
WHERE user_id = '$userid'
order by ID desc limit 1
You can do a subquery.
SELECT * FROM `stats` WHERE user_id = '$userid' WHERE ID = (SELECT MAX(ID) FROM your_table)
See Abhik Chakraborty's answer if the higher ID you search is from the "stats" table. It's answer is a lot better :)
try this query.
SELECT * FROM mytable WHERE postID=(SELECT MAX(userID) FROM mytable)

MySQL inner join 2 tables to match user number to user name

I'm sorry this has probably been answered hundreds of time but I'm totally lost between different scenarios here.
What I want is pretty simple. I have 2 tables "bets" and "users".
In the table "bets", I put the UserID instead of the UserName. In the table "users", the UserName is linked to the UserID.
I would like to be able to read the data from the table "bets" and display the UserName instead of the UserID, so I will need some sort of code to match the UserID contained in the table "bets" and return the UserName instead.
The MySQL query I have for now:
$sql5="SELECT * FROM Bets, Users WHERE GameID = '$NGnumber' ORDER BY DrawOrder";
$result5 = mysql_query($sql5) or die(mysql_error());
while($rows5 = mysql_fetch_assoc($result5)){
...
I can easily echo $rows5['UserID'] but I would like the UserName (in the Users table) instead. How can I do that?
Thanks!
Use inner join:
SELECT * FROM Bets INNER JOIN Users ON Bets.userID = Users.userID WHERE GameID = '$NGnumber' ORDER BY DrawOrder
Replace the query:
SELECT * FROM Bets b INNER JOIN Users u
ON b.GameID = u.GameID
WHERE GameID ='$NGnumber' ORDER BY DrawOrder"

Mysql Join without replacing value of original id

I am trying to join my users table with another table using the following query...
SELECT * FROM (`activities`)
JOIN `users` ON `users`.`id` = `activities`.`user`
WHERE `user_subdomain` = 'hi' OR user_subdomain = ''
ORDER BY `activities`.`id` desc
LIMIT 10
Is there any way to do the join so that the id of the user does not replace the id of the activity?
For example, currently if there is an activity with the id of 10 and the user 2 the id will be replaced by the id of the users table and show as 2 after I run the query.
Thanks a lot for the help!
Whenever you are joining tables, you ought to be explicit about the columns you select rather than using SELECT *, and specify column aliases for them when the same column name is used in multiple tables.
SELECT
activities.id,
activities.othercol,
/* Alias to userid */
users.id AS userid,
users.name,
users.anothercolumn
FROM (`activities`)
JOIN `users` ON `users`.`id` = `activities`.`user`
WHERE `user_subdomain` = 'hi' OR user_subdomain = ''
ORDER BY `activities`.`id` desc
LIMIT 10
Though it isn't strictly necessary to prepend the table name to each, unless the column names are the same.
SELECT
activities.id AS activityid,
othercol,
users.id AS userid,
name,
anothercolumn

How to select first and last data row from a mysql result?

SELECT * from User returns 75 users. Is it possible to select 1st user, and 75th user without doing while($row = mysql_fetch_assoc($result)) ?? and how?
UPDATE
Just to be more clear: I need to have SELECT * as I need the first and 75th user before I do while mysql_fetch_assoc so ASC, DESC, LIMIT answers not required.
SELECT * from User LIMIT 1
UNION
SELECT * from User LIMIT 74,1
Edit
#Kay: PHP can't change the internal order of the resultset after it's created.
If the query always returns 75 rows then the only way to access the 1st and the 75th before anything else would be to use mysql_data_seek which moves the internal result pointer:
$result = mysql_query('SELECT * from User');
mysql_data_seek($result, 1);
$row1 = mysql_fetch_assoc($result);
mysql_data_seek($result, 75);
$row75 = mysql_fetch_assoc($result);
Note that if the above is followed by a while, the pointer must be reset to a suitable position.
If you can sort it, you can.
Select * from User order by [something] asc limit 1
and
Select * from User order by [something] desc limit 1
Assuming you have 'id' as a primary key and you need the last one (not the 75th one) you could try something like:
SELECT * FROM User WHERE id IN ((SELECT min(id) FROM user b), (SELECT max(id) FROM user c))
SELECT
(SELECT column FROM table WHERE [condition] ORDER BY column LIMIT 1) as 'first',
(SELECT column FROM table WHERE [condition] ORDER BY column DESC LIMIT 1) as 'last'
SELECT u.*
FROM Users u
INNER JOIN (
SELECT MIN(UserID) AS UserID FROM Users
UNION ALL SELECT MAX(UserID) FROM Users
) um ON um.UserID = u.UserID
Edit
I'm not sure I completely understand what you need but following gets the first and last user followed by everyone else.
SELECT um.SortOrder, u.*
FROM Users u
INNER JOIN (
SELECT 1 AS SortOrder, MIN(UserID) AS UserID FROM Users
UNION ALL SELECT 2, MAX(UserID) FROM Users
) um ON um.UserID = u.UserID
UNION ALL
SELECT 3 AS SortOrder, u.*
FROM Users u
LEFT OUTER JOIN (
SELECT MIN(UserID) AS UserID FROM Users
UNION ALL SELECT MAX(UserID) FROM Users
) um ON um.UserID = u.UserID
WHERE um.UserID IS NULL
ORDER BY
SortOrder
Well, the title of your question is a bit different from the explanation you gave.
I say so cos if you want to select first and last row, it might be different to select 1st and 75th row cos in case the rows increase or reduce, the last might not be the 75th row.
To answer the part of the first and last row, i think you can do this.
select distinct(id) from users where id in ((select max(id) from user), (select min(id) from users));
This query will work well in the hope that users are ordered by id.
But if you are talking about the 1st and 75th row, then i'll settle with #Saul's answer .
Hope this helps.

Categories