I want the database to show all the rows, except for the first and last ones, since I have CSS code for them.
I tried this:
SELECT * FROM db
WHERE
keywords LIKE '%example%' LIMIT 9999 OFFSET 1
AND
keywords LIKE '%example%' DESC LIMIT 9999 OFFSET 1
Since the row number may increase I can't write an exact number.
There really is no reason to complicate your query by trying to snip off these values at the SQL level, you could do:
$results = $db->query( /* regular query with all results */ );
array_pop($results);
array_shift($results);
// Now use $results, which now contains only the "middle" content
If you really want it at the DB level, you can use:
SELECT * FROM db
WHERE keywords LIKE '%example%'
AND id <> (SELECT MAX(ID) FROM TABLE)
AND id <> (SELECT MIN(ID) FROM TABLE)
You can use UNION like as
SELECT * FROM db WHERE keywords LIKE '%example%' order by keywords ASC limit 1 UNION SELECT * FROM db WHERE keywords LIKE '%example%' order by keywords DESC limit 1;
You can try this for instance:
SELECT * FROM TABLE WHERE ID != (SELECT MAX(ID) FROM TABLE) LIMIT 1,9844674507370
But like I said in the comment : It is strongly advisable that you handle this with PHP code, to avoid making 2 or more requests
You can do it without using LIMIT AND OFFSET
SELECT * FROM table_name WHERE id != (SELECT MAX(id) FROM table_name) AND id != (SELECT MIN(id) FROM table_name)
SELECT * FROM db
WHERE
keywords LIKE '%example%'
AND
id != (SELECT MAX(id) FROM db)
AND
id != (SELECT MIN(id) FROM db)
here id will be your auto increment key
1st : Simple you can handle this thing in php like below . avoid two query
$last_record =count($records)-1;
$i=0;
foreach($records as $key=>$row)
{
if($i==0){
//apply the css
}
if($i== $last_record ){
//apply the css
}
}
query :
SELECT * FROM db WHERE keywords LIKE '%example%'
Related
I would like to get number of all records and get last record :
$sql_count_sms = "SELECT count(*) as total,content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
$result_count_sms = mysql_query($sql_count_sms);
$row_num_sms = mysql_fetch_assoc($result_count_sms);
$num_sms = $row_num_sms['total'];
$last_my_sms = $row_num_sms['content'];
I can get number of records but I can't get last content record .
It returns first record !
Where is my wrong ?
Below codes works fine, but I think count(*) is faster than mysql_num_rows .
$sql_count_sms = "SELECT content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
$result_count_sms = mysql_query($sql_count_sms);
$row_num_sms = mysql_fetch_assoc($result_count_sms);
$num_sms = mysql_num_rows($result_count_sms);
$last_my_sms = $row_num_sms['content'];
Any solution?
The grain of the two results you want is not the same. Without using a sub-query you can't combine an aggregate and a single row into the same result.
Think of the grain as the base unit of the result. The use of GROUP BY and aggregate functions can influence that "grain"... one result row per row on table, or is it grouped by user_id etc... Think of an aggregate function as a form of grouping.
You could break it out into two separate statements:
SELECT count(*) as total FROM android_users_sms WHERE user_id = :id;
SELECT * FROM android_users_sms WHERE user_id = :id ORDER BY id DESC LIMIT 1;
Also, specific to your question, you probably want a LIMIT 1 in combination with the ORDER BY to get just the last row.
Now, counter intuitively perhaps, this should also work:
SELECT count(*), content, id
FROM android_users_sms
WHERE user_id = :id
GROUP BY id, content
ORDER BY id
LIMIT 1;`
This is because we've changed the "grain" with the GROUP BY. This is the real nuance and I feel like this could probably be explained better than I am doing now.
You could also do this with a sub query like so:
SELECT aus.*,
(SELECT count(*) as total FROM android_users_sms WHERE user_id = :id) AS s1
FROM android_users_sms AS aus
WHERE user_id = :id ORDER BY id DESC LIMIT 1;
Look at my code, I want the select statement order by the count percentage after I fetch the data from this select statement, obviously, it's not logical. What can I do? Help, appreciate.
<?php
//myslq connection code, remove it because it's not relate to this question
$stm =$db->prepare("SELECT id ,term_count, COUNT(user_id) as count FROM sign WHERE term IN (:term_0,:term_1) GROUP BY user_id ORDER by count DESC");
//trying replace order by count with $combine_count, but it's wrong
$term_0="$term[0]";
$term_1="$term[1]";
$stm->bindParam(":term_0", $term_0);
$stm->bindParam(":term_1", $term_1);
stm->execute();
$rows = $stm->fetchALL(PDO::FETCH_ASSOC);
foreach ($rows as rows) {
$count=$rows['count'];
$term_count_number=$rows['term_count'];
$count_percentage=round(($count/$count_user_diff)*100);
$count_key_match=round(($count/$term_count_number)*100);
$combine_count=round(($count_percentage+$count_key_match)/2);
//issue is here, I want the select statement order by $combine_count
}
?>
SELECT id ,term_count, COUNT(user_id) as `count`
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY user_id
ORDER by `count` DESC");
Since "count" is a function, it would be better to put backtics around the non-function "counts", as done above.
GROUP BY should list the field not aggregated. Otherwise, it does not know which id and term_count to fetch. So, depending on what you are looking for,
Either do
SELECT user_id, COUNT(*) as `count` -- I changed this line
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY user_id
ORDER by `count` DESC");
or do
SELECT id ,term_count, COUNT(*) as `count`
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY id ,term_count -- I changed this line
ORDER by `count` DESC");
SQL Syntax Logic
SELECT column1, count(column1) AS amount
FROM table_name
GROUP BY column1
ORDER BY amount DESC
LIMIT 12
First I need to get exact match like
SELECT * FROM movies WHERE title='STRING' ORDER BY x DESC
and then append to these results query with LIKE match
SELECT * FROM movies WHERE title LIKE '%STRING&' AND title<>'STRING' ORDER BY x DESC
and limit these results with maximum of 10 results.
UNION wont`t do the jobs as it sorts all results together and returns wrong order (I need exact match first, then with LIKE)
SELECT * FROM movies WHERE title='STRING' UNION
SELECT * FROM movies WHERE title LIKE '%STRING%' ORDER BY x DESC LIMIT 10
The best solution I got is to use multi_query()
$query = "SELECT * FROM movies WHERE title='STRING' ORDER BY x DESC; ";
$query .= "SELECT * FROM movies WHERE title LIKE '%STRING%' AND title<>'red' ORDER BY x DESC";
$Dbi->multi_query($query);
do {
$sql = $Dbi->store_result();
while($x = $sql->fetch_array()) {
...
}
} while($Dbi->next_result());
but in this case it is not possible to use any mysql inside the inner loop and there also must be better looking solution!
You can do this with one query, by using the order by clause:
SELECT *
FROM movies
WHERE title like '%STRING%'
ORDER BY title = 'STRING' desc,
title like '%STRING%' desc
LIMIT 10;
The first clause in the ORDER BY puts the exact matches first. The second then orders by the partial matches. The WHERE clause ensures that there is a match of some kind.
You don't need the UNION, it's accessing the same table twice:
SELECT *
FROM movies
WHERE title LIKE '%STRING&'
ORDER BY CASE WHEN title='STRING' THEN 1 ELSE 2 END
LIMIT 10
(SELECT * FROM movies WHERE title='STRING')
UNION
(SELECT * FROM movies WHERE title LIKE '%STRING%' ORDER BY x DESC LIMIT 10)
I tried using distinct as well and it returns duplicates.
$cubes = mysql_query("SELECT distinct * FROM posts ORDER BY RAND() $limit ") or die(mysql_error());
I just want to take my posts table... and return it in a random order without duplicates.
Select only the distinct id's you need, e.g.
SELECT distinct id FROM posts ORDER BY RAND() $limit
Distinct works over 'all' rows you select, so if you (for example) have a unique timestamp field, chances are you'll return every single row.
Are you sure that you want to execute a SELECT DISTINCT * FROM ... and not just a SELECT DISTINCT column_name FROM ... ?
See the SQL DISTINCT STATEMENT doc for more infos.
I am looking for a better way of doing this:
SELECT * FROM $tbl_name WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM $tbl_name ) ORDER BY id LIMIT 1;
It is slow and isn't very random, I get the same result every 10 or so query's.
This selects a random row from the table regardless of its ID.
So far I have this:
// Get amount of rows in database
$result = mysql_query("SELECT * FROM $tbl_name");
$num_rows = mysql_num_rows($result);
// Generate random number
$random_row = rand(1, $num_rows);
But I don't know how to get a certain row.
I do not mean
SELECT * FROM $tbl_name WHERE id = $random_row
Because my database has gaps in the ID column so it would sometimes fail.
Has anyone got script that can get a random result from a MySQL database without replying on IDs and is super fast? (the database contains about 20000 rows)
SELECT * FROM $tbl_name WHERE 1 ORDER BY RAND() LIMIT 1;
20,000 rows isn't really that much, the above should be fast enough.
Juhana is right by the book: "ORDER BY RAND() LIMIT 1", and of course 20k isn1t that much.
Other option will be with subselects:
SELECT [fields]
FROM myTable,
(SELECT FLOOR(MAX(myTable.id) * RAND()) AS randId FROM myTable) AS someRandId
WHERE myTable.id = someRandId.randId
discussed here
(please avoid select * when it`s unnecessary)
After some searching though the comments on the link Adi sent, I have found a decent solution.
SELECT * FROM $tbl_name T JOIN (SELECT CEIL(MAX(ID)*RAND()) AS ID FROM $tbl_name) AS x ON T.ID >= x.ID LIMIT 1;
Source: wanderr.com/jay/order-by-slow/2008/01/30
Seems to be very fast and very random!