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

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.

Related

show users the position after sorting based on score

I have a table which has the id column and score column, I want to sort the table based on score column and then find the specific user who is loading the page and show him his/her position. for example, tell him "your position is 40th".
Well I know how to sort a query:
SELECT id,score FROM `table` ORDER BY `score` DESC
But after the sort how can I find an specific id's position?
You don't need an order by for this. Instead:
select 1 + count(*)
from table t
where t.score > (select t2.score from table t2 where id = $id);
Try it:
SELECT #rownum:=#rownum+1 ‘rank’, id, score FROM table t, (SELECT #rownum:=0) r ORDER BY score DESC;
This will create a column and increase 1 in each record.

Need the highest ID using left join

I have two tables,
TABLE 1 has many of each client and campaign and is very large
TABLE 2 has only one of each client and campaign and is small.
So I want to get the lastest(highest ID) from TABLE 1 where it matches the client and campaign in TABLE 2 and only one of each.
I have tried MAX, and playing with the order by etc, but cant get it working....
The results I get are choosing the lowest ID from TABLE 1 (I want highest)
$result2 = mysql_query("SELECT table1.client,table1.campaign,table1.id
FROM table1
LEFT OUTER JOIN
table2
ON (table2.client = table1.client)
AND (table2.campaign = table1.campaign )
WHERE (table2.enabled != 'disabled')
group by campaign asc
order by client,campaign,id asc
");
Help needed....
SELECT * FROM table1
INNER JOIN
(
SELECT MAX(table1.id) AS id FROM table1
INNER JOIN table2 ON table2.client = table1.client AND table2.campaign=table1.campaign and table2.enabled != 'disabled'
GROUP BY table1.client, table1.campaign
) AS m ON m.id = table1.id
I think that's what you're asking for. For each combination of client and campaign that exists in each table, it will give you the highest ID in table 1.

Returning the last two set of records mySQL

well, i'm new to MySQL Database and i got a problem, i need to get the last two set of records from a table ( the records are automatically added to this table every week) i need to use to find the growth that an entity did during the last week.
can any one help plz.
here is what i wrote, i tested it on my local host and it worked :D, but when we installed it online, it crashed :(
select pages.*, new.* from (
select id, tableone.page_id, one, two,(two - one) as diff from
(SELECT id, page_id, likes as two FROM `page_records` WHERE id IN ( SELECT max( id ) FROM `page_records` GROUP BY page_id )) as tableone left join
(SELECT page_id , likes as one FROM `page_records` where id in ( SELECT max(id) FROM `page_records` where id not in (select max(id) from `page_records` group by page_id) group by page_id))
as tabletwo
on tableone.page_id = tabletwo.page_id
order by tableone.page_id asc) as new inner join pages on pages.id = new.page_id
Thanks in advance.
try:
SELECT id, page_id, likes FROM page_records order by id desc limit 0, 2
Try this:
SELECT * FROM table_name
ORDER BY id DESC
LIMIT 0, 2
Thanks!

SQL: Check if value is available in tbl1 or tbl2

I want to create a sub-account system (PHP & MYSQL).
I have a user table (users) and a sub users table (sub_users).
How can check if the user is available in the user table, or in the sub users table?
My code:
SELECT DISTINCT *
FROM users
WHERE userid = "steven"
OR WHERE EXISTS (SELECT *
FROM sub_users
WHERE sub_users.userid = "steven");
ERROR: Check your syntax near "steven"
Also tried:
SELECT *
FROM users
LEFT JOIN sub_users
ON sub_users.user_userid = users.userid
WHERE users.userid = 'steven'
OR sub_users.userid = 'steven'
Same error.
In the first place, you only want one where clause. I would also use single quote instead of double quotes:
SELECT DISTINCT *
FROM users
WHERE userid = 'steven' or
EXISTS (SELECT *
FROM sub_users
WHERE sub_users.userid = 'steven'
);
I doubt you need the distinct keyword, if you are fetching all the columns from users.
Your second query looks ok. Are you sure you are not running the first query twice?
EDIT:
I'm trying to figure out what you want to return. The following returns 1 if 'steven' appears in either table and 0 otherwise:
select (case when exists (select 1 from users where users.userid = 'steven') and
exists (select 1 from sub_users where sub_users.userid = 'steven')
then 1
else 0
end);
This method saves on the overhead of a join and will readily take advantage of indexes on users(userid) and sub_users(userid).
You could also use a union:
(SELECT userid FROM users WHERE userid = 'steven')
UNION
(SELECT userid FROM sub_users WHERE userid = 'steven');
select * from
(select * from users) x,
(select * from sub_users) y
where x.user_id = 'steven' or y.user_id = 'steven'
Good luck !!!

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

Categories