How can I select the next result just by specifying the name?
I have a table that looks like this, no IDs, just list of usernames.
row1 = username(Alex)
row2 = username(Bob)
row3 = username(Britney)
row4 = username(Steve)
row5 = username(Courtney)
row6 = username(Greg)
row7 = username(Abul)
row8 = username(Roger)
row9 = username(Victoria)
row10 = username(Brooke)
Let's say, I want to select all Items after 'Greg'. How can I achieve this?
No, there is no inherent ordering of tables in SQL, so there is no way (other than by alphabetical order) to determine which name comes next.
In fact, the order displayed in the question is entirely arbitrary - without a specified order by clause, retrieval order of rows is essentially random.
this can be done by two query..first find the id of the particular name.
like select id from tablename where username='Greg'
then fetching that id,
select * from tablename where id>fetching id.
Add ID column to your table, and then use LIMIT as offset
SELECT * FROM users LIMIT (SELECT ID FROM username WHERE username='Greg'), MAX(ID)
Didn't tested, but you can play with it
Related
I have a simple table in phpmyadmin called name with only 1 column id which is look like this
id
--------
a
b
a
a
a
a
b
Now i want to show most used id on my PHP page.
Here is my code:
$sql_a = mysql_query(SELECT id FROM name WHERE id='a');
$count_a = mysql_num_rows($sql_a);
$sql_b = mysql_query(SELECT id FROM name WHERE id='b');
$count_b = mysql_num_rows($sql_b);
if($count_a > $count_b)
{
$most_used_id = "A";
}
else
{
$most_used_id = "B";
}
echo "<h1>MOST USED ID IS $most_used_id</h1>";
Currently I have only 2 types of id but in future I will have multiples (maybe 300+) id's, so is there a way to make query dynamic and get only most used value
That's very redundant code. You'd be better off with
SELECT id, count(id) AS cnt
FROM name
ORDER BY cnt DESC
GROUP BY id
LIMIT 1
that'll give you the "most popular" id value, and just how popular it is. If you need to get the count of all the ids, then remove the limit line.
Try the following query:
select id, count(id) cnt
from name
group by id
order by cnt desc
limit 1
This is basic but I can't figure it out. I have two tables (SeriesTable and OtherTable). SeriesTable has all the information for a given series including its id (column named "seriesid"). And OtherTable has a column called "seriescolumn" which also has the ids of a given series.
I need to make a query that counts every entry in OtherTable's "seriescolumn" that matches the seriesid column in SeriesTable. So for example, if the seriesid in SeriesTable is 5, I need to count how many entries in OtherTable have the value of 5 in the seriescolumn.
Below is my current code that simply grabs the info from the first table, but I have no idea how to correctly count the matching entries from OtherTable.
<?
$rs= mysql_query("SELECT seriesid FROM SeriesTable ORDER BY seriesid DESC");
while ($row= mysql_fetch_array($rs)) { ?>
content
<? } ?>
Sounds like you are going to need a join and group by statement.
SELECT s.seriesid, Count(*) As NumberOfSeries
FROM SeriesTable s Join
OtherTable o On s.seriesid = o.seriescolumn
Group By s.seriesid
ORDER BY seriesid DESC
This should return each seriesid and a count of how many times it was repeated.
Probably the easiest way to do this is in one big SQL query, using the count statement.
You can use a GROUP BY clause to group the result by the seriesid as you want, giving something along the lines of:
SELECT seriesid, COUNT(*) FROM SeriesTable, OtherTable
WHERE seriescolumn=seriesid GROUP BY seriesid
SELECT seriesid, COUNT(seriescolumn)
FROM SeriesTable, OtherTable
WHERE OtherTable.seriescolumn = SeriesTable.seriesid
GROUP BY seriesid;
I have a table ipaddresses that contains IP ranges. Columns are: ipStart, ipEnd
Example of
ipStart: 3579374832
ipEnd: 3579374839
Now I want to select 300ish IP addresses from another table: visit_count. And based on those 300 addresses I want to check if the ip address is in the range of any of IPs in the table ipaddresses
My current code:
$results = $database->query("SELECT user_id,
DATE_FORMAT(last_visit, '%Y-%m-%d') as datumet,
cookieId, ipaddress
FROM `visit_count`
WHERE last_visit BETWEEN
'$firstDayOfMonth' AND '$lastDayOfMonth'
AND user_id = '$userId'
GROUP BY cookieId
ORDER BY last_visit ASC");
$rows = $database->loadObjectList($results);
foreach ( $rows as $row ) {
$ipaddressLong = ip2long($row->ipaddress);
// This is where its very very slow
$selO = $database->query("SELECT ipStart, ipEnd FROM `ipaddresses`
WHERE '$ipaddressLong' BETWEEN `ipStart` AND `ipEnd`");
$rowO = $database->getrow($selO);
}
The result is a really slow query that consumes a lot of cpu.
ipaddresses has indexes for both ipStart and ipEnd and contains around 50k rows.
How can I make this go faster?
A quick and dirty change to a single query using a JOIN:-
SELECT a.ipStart, a.ipEnd
FROM `ipaddresses` a
INNER JOIN
(
SELECT user_id, DATE_FORMAT(last_visit, '%Y-%m-%d') as datumet, cookieId, inet_aton(ipaddress ) AS ipaddressLong
FROM `visit_count`
WHERE last_visit BETWEEN '$firstDayOfMonth' AND '$lastDayOfMonth'
AND user_id = '$userId'
GROUP BY cookieId
) b
ON b.ipaddressLong BETWEEN a.ipStart AND a.ipEnd
Note that this could probably be simplified. However it depends on your use of GROUP BY cookieId . At the moment this is going to get one row per cookie id, but which row is undefined (ie, could be any user_id, ip address and last visit date that goes with that cookie id).
You can simplify the first select. You don't need to select any fields beyond ipaddress. You also don't need to order or group the result. If you want unique ipaddresses, just use distinct
select distinct ipaddress
from visit_count
where last_visit between '$firstDayOfMonth' and '$lastDayOfMonth'
and user_id = '$userId'
300 selects don't seem to be much, even with the second table having 50k rows. On my machine, even without indexes, it takes only a fraction of a second.
If you want to simplify it anyway, you can join the two tables with
select ipstart, ipend
from ipaddresses i
join visit_count v on inet_aton(v.ipaddress) between i.ipstart and i.ipend
where v.last_visit between '$firstDayOfMonth' and '$lastDayOfMonth'
and v.userid = '$userId'
1) Use better query like other suggested to you
2) Have you defined indexes for the field you need ?
3) Dont know if you use mysql or mysqli...anyway use fetch_assoc that is faster then fetch_array
with this 3 trick you should be ok
I would like to get one value instead of all values when they have the same name.
within an sql query. Im using fullcalendar. and have two tables one for the events(evenement) and one for the receiver(evenementontvanger).
evenementontvanger:
id idEvent
1 231
2 231
3 231
evenement:
id title
231 hello
I would like to show only one title not 3
my sql query:
"SELECT
*
FROM
`evenement`
JOIN
`evenementontvanger` ON `evenementontvanger`.`idEvent` = `evenement`.`id`
WHERE
`idEvent` = `evenement`.`id`"
You can use distinct to do so as
SELECT distinct `evenementontvanger`.`idEvent`,`evenement`.`title`
FROM
`evenement`
JOIN
`evenementontvanger` ON `evenementontvanger`.`idEvent` = `evenement`.`id`
WHERE
`idEvent` = `evenement`.`id`;
How ever the above will not bother about idWerknemer and if you want to display them as group use Group_concat as
SELECT `evenementontvanger`.`idEvent`,
`evenement`.`title`,
group_concat(`evenementontvanger`.`idWerknemer`) as `idWerknemer`
FROM
`evenement`
JOIN
`evenementontvanger` ON `evenementontvanger`.`idEvent` = `evenement`.`id`
WHERE
`idEvent` = `evenement`.`id`
Group By `evenementontvanger`.`idEvent`
Check the demo here http://sqlfiddle.com/#!2/290b4/13
Use SELECT DISTINCT on your query to eliminate duplicates :
The ALL and DISTINCT options specify whether duplicate rows should be
returned. ALL (the default) specifies that all matching rows should be
returned, including duplicates. DISTINCT specifies removal of
duplicate rows from the result set. It is an error to specify both
options. DISTINCTROW is a synonym for DISTINCT.
From MySQL docs
use either top 1
OR
select distinct
I'm writing a simple URL rotator for a client and they want the URLs to rotate according to the oldest one that was previously displayed.
My columns are very simple:
url_id | company_id | url | last_clicked
I want to fetch a single row where the company_id is passed in and the last_clicked is the minimum of all records matching the company_id.
It should also select a random url_id if all last_clicked values are empty.
I assume this can be accomplished with a GROUP BY and HAVING but I can't seem to get the query to return anything.
I have this:
$last = $this->db->fetchOne ("SELECT url_id FROM
{$this->prefix}urls GROUP BY company_id HAVING MIN(last_clicked)
WHERE company_id='$company'");
This will fetch the row where last_clicked is smallest, or at random if they are all NULL:
SELECT url_id FROM urls
WHERE company_id = $company
ORDER BY last_clicked, RANDOM() LIMIT 1;
An index based on company_id and last_clicked would greatly help:
CREATE INDEX urls_ndx ON urls(company_id, last_clicked);
SELECT url_id FROM
TABLE
WHERE company_id='$company'
AND last_clicked = ( SELECT MIN(last_clicked)
FROM TABLE WHERE company_id='$company' )