MySQL Query (database) - trying to display only certain values - php

Hello there i am having little problem. I have two tables in my database.
As you can see i am getting all employees in one tab, and what i am trying to achieve here is to display only relevant employees in given tab. So employees from Customer services wont be displayed in Sales tab for example.
$query = mysql_query("SELECT * "."FROM employees, dept_emp "."WHERE employees.emp_no = dept_emp.emp_no");
Thank you for looking and help :)

Your WHERE clause is useless as it is just restating a JOIN condition basically. Try this:
SELECT *
FROM employees AS e
INNER JOIN dept_emp AS de ON e.emp_no = de.emp_no
WHERE de.dept_no = '?'
Obviously the ? would be substituted with the dept_no value you are actually trying to filter on.
Per your question about seeting query limits/pagination, that is done via SQL LIMIT clause. The clause can be expressed in a few different ways.
This first just returns a max number of rows:
LIMIT 100 <-- shows first 100 rows from the result set
The following two forms of syntax are used for pagination of results:
LIMIT 0, 100 <-- show first 100 rows from the result set (start at 0 offset, and return a max of 100 rows
LIMIT 100, 100 <-- show rows 101-200 from the result set (start at 100 offset and return max of 100 rows)
Or:
LIMIT 100 OFFSET 0 <-- first 100 rows
LIMIT 100 OFFSET 100 <-- rows 101-200
So putting it all together
SELECT *
FROM employees AS e
INNER JOIN dept_emp AS de ON e.emp_no = de.emp_no
WHERE de.dept_no = '?'
ORDER BY e.emp_no
LIMIT 0,100
Note that I also added an ORDER BY clause. This is important for pagination in that just a regular unordered SELECT doesn't guarantee order. If you tried to paginate without an ORDER BY you could potentially get the same row returned in multiple "pages".

It doesn't appear you are limiting the departments. The where clause needs a hard limit, your where will always match everything. Also, why are you concatenating your statement? It doesn't break.
Something like:
$query = mysql_query("SELECT * FROM employees JOIN dept_emp ON employees.emp_no = dept_emp.emp_no WHERE dept_emp.dept_no = 'd007'");

$dept = ?;
$query = mysql_query("SELECT *
FROM employees, dept_emp
WHERE employees.emp_no = dept_emp.emp_no
AND de.dept_no = $dept
");

Related

How select next row pagination in sql

I'm sorry I'm weak for English.
i echo 2 row in each page . how echo next 2 row
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category
WHERE mzmx_post.id = mzmx_post_category.post_id AND zmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2
You can use the two-arguments form of LIMIT to offset the result by a given number of rows, like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5
ORDER BY id DESC
LIMIT 2, 2 -- fetch records 3 and 4
This gives you the second page. If you want the third page, then:
LIMIT 4, 2
And so on.
Note that I modified your query so the joining condition between the tables is placed in the ON clause of the join rather than in the WHERE clause.
Better add one extra column (e.g. mzmx_post_key bigint) of Long type in each table and have sequential value on that column. Use that column to fetch data from DB from page wise.
sqL suery should look like:
SELECT *
FROM `mzmx_post`
JOIN mzmx_post_category ON mzmx_post.id = mzmx_post_category.post_id
WHERE mzmx_post_category.category_id = 5 and mzmx_post_key> ##last record key##
ORDER BY mzmx_post_key ASC
LIMIT 2
The basic idea is to use
LIMIT n,o
where n is the results per page
o is the offset from the first result
for the p-th page the offset would be
o = p * n
where p = 0,1,2,....

PHP & MYSQL - ORDER BY id sometimes returns nothing

I am trying to wrote a PHP script that will pull a random row from a MYSQL table. So far, the code successfully grabs a random row, but sometimes it will return nothing, and I don't understand why.
$result = $conn->query("SELECT fact
FROM numfacts
WHERE number = '".(string)$number."'
AND id >= (SELECT FLOOR( MAX(id) * RAND()) FROM numfacts )
ORDER BY id
LIMIT 1");
The value for $number is currently 12, and there are two rows containing this in the database. Roughly 2/3 times the code returns a value, and the other 1/3 of times it returns 0 results.
If you need more code, I will provide it.
The part of the WHERE clause with id >= (SELECT FLOOR( MAX(id) * RAND()) FROM numfacts ) restricts the query to looking in a subset of the table. If the two rows with number = 12 are not in this subset, the query doesn't return anything. And since the subset is specified randomly, this will only happen some of the time.
To ensure that the subset includes at least one of the rows with number = 12, you can include that criteria in the subquery.
SELECT fact
FROM numfacts
WHERE number = '".(string)$number."'
AND id >= (SELECT FLOOR( MAX(id) * RAND())
FROM numfacts
WHERE number = '$number' )
ORDER BY id
LIMIT 1
Note that this query doesn't provide very fair selection of rows. Because it uses ORDER BY id, it's biased towards low-numbered rows. This method is reasonable when you're just trying to select a random row with no other filtering, but when you add the number = 12 criteria it becomes unfair. For instance, if the IDs of the two rows are 50 and 75, you'll choose the lower one 2/3 of the time.
You can get an unbiased selection with:
SELECT fact
FROM numfacts
WHERE number = '$number'
ORDER BY RAND()
LIMIT 1
If subquery SELECT FLOOR( MAX(id) * RAND()) FROM numfacts will return something less then $number the entire query will return nothing.

Mysql select last 20 rows, with while loop

I have 50+ rows and each have an id, how do i get the last 20 records and display each ones information with php.
Is the best way to use a loop? I want it to display the results quick and not miss any rows, is a loop the best way to go then?
This is the code that I have
$result = $mysqli_log->query("SELECT * FROM `$usern`");
while( $row = $result->fetch_array() ) {
$credit = $row['credit'];
echo $credit;
}
The MySQL query being executed doesn't specify any "order" to the rows; MySQL is free to return the rows in any order it chooses, so it's possible that the "last 20" rows on one run of the query might differ from the "last 20" rows on a second run.
(We do observe repeated behavior when the statement is re-executed; it usually takes some DML operations, the addition of an index, or an OPTIMIZE table statement, to actually get a change in the results returned... but the point is, there is no "last 20" rows in the table. In MySQL, it's just a set of rows.)
To specify a specific sequence of the rows, add an ORDER BY clause to the query. Assuming that you want to use the unique id column to order the rows, and you want the last 20 rows, and you want them returned in ascending id sequence:
SELECT t.*
FROM ( SELECT u.*
FROM `$usern` u
ORDER BY u.id DESC
LIMIT 20
) t
ORDER BY t.id
And, yes, processing rows "in a loop" in PHP, just like you demonstrate, is a normative pattern.
To limit the number of queries use Limit and order them desc by your ID
Select *
From `$usern`
Order By ID Desc
Limit 20
To Flip them back in the forward order you can use a derived table
Select *
From (Select ID, Test
From test
Order By ID Desc
Limit 3) d
Order By ID Asc
If you need the newest 20 records, you have to ORDER DESC the result set by ID and then LIMIT that set result to 20 records.
So you can
use something like this:
$result = $mysqli_log->query("SELECT * FROM `$usern` ORDER BY `ID` DESC LIMIT 20");
while( $row = $result->fetch_array() ) {
$credit = $row['credit'];
echo $credit;
}
Another good approach, if you are using associative keys like $row['credit'], is to use featch_assoc instead of featch_array (if your framework provides such a function)

Mysql query picking highest ID using "WHERE IN" and LIMIT, not returning enough results

PROBLEM:
This query will only show the correct answer if I change the LIMIT to however how many results are in my IN statement.
AIM: - I want the amount in my variable(Car,Van,Bike,Bus) to equal the amount on the limit.
My IN statement is actually a variable that changes and can have from 1-50 items (truck, taxi etc), but for ease I have used 4. If it has 3 items them I have to change the LIMIT to 3 and so on.
I could do a query, then explode into array, and count items the use this number as a variable to add to the limit, but that's 2 queries!
Easy to read query: -
$result = mysql_query("SELECT total FROM table1 WHERE client='$client'
and campaign IN ('Car', 'Van', 'Bike', 'Bus') ORDER BY id DESC limit 4");
The car,van,bike and bus come from a database query themselves....
$result = mysql_query("SELECT rules FROM combined WHERE groupname='$groupname'");
This produced 'Car', 'Van', 'Bike', 'Bus'
Mock data: -
Car = 1,
Van = 2,
Bike = 3,
Bus = 4.
Answer on this query is 1+2+3+4
But if I had a rule where there were 5 in the campaign IN part it would be the same, as it is only fetching 4 answers not 5.
So its still only adding 1+2+3+4, as the limit is 4 not now 5.
The bold parts are actually stored in the database with slashes added.
$rule = 'Car', 'Van', 'Bike', 'Bus';
The real mysql statement is below: -
$result = mysql_query("SELECT total FROM table1 WHERE client='$client'
and campaign IN ($rule) ORDER BY id DESC limit 4");
=======================================================================
Explanation
The following query gets me this data ('Car', 'Van', 'Bike', 'Bus')
$result = mysql_query("SELECT rules FROM combined WHERE groupname='$groupname'");
I place this in a variable called $rule
I then run this query
$result = mysql_query("SELECT total FROM table1 WHERE client='$client'
and campaign IN ($rule) ORDER BY id DESC limit 4");
This will return a number for each of these (total for Car = 1, total for Van = 2)
Problem is that when there is more than 4 in my $rule it wont return more than 4 because of the limit. I would have to change it everytime.
Can I combine the two querys....and get the highest id of each of the Car,Van, Bike campaigns. (that appear in my IN statement or $rule)
Hopefully this makes it clearer.
I'm not sure this is really what you need, but it answers my interpretation of the question:
SELECT total
FROM table1
JOIN (
SELECT MAX(id) as id
FROM table1
WHERE campaign IN ('Car', 'Van', 'Bike', 'Bus')
GROUP BY campaign
) t ON t.id = table1.id

mysql - how to count how many records there are in a table and then only get 20?

I'm building a forum for a school project and I want to display only say 20 posts per page, for a forum. However, I still need to know how much total posts there are, to display the page listing.
I could run a mysql query that limits the number of posts to 20, and then, run another query that would count how many records there are in a table, but that would be 2 queries. Isn't there a way to both get a limited number of records AND in the same query, to get the number of records total?
Thanks.
You can use a subquery
select *,
(select count(*) from your_table) as total_count
from your_table
order by some_column
limit 20
I'm expanding juergen's post:
$result = mysql_query("SELECT * (SELECT COUNT(*) FROM table) AS total FROM tablePRDER BY id LIMIT 0, 20");
while($row = mysql_fetch_assoc($result))
{
$total = $row['total']; /* Total rows of the whole table */
$id = $row['id']; /* Id of limitted query (20) */
}
select *
from your_table
inner join (select count(*) as total_count from your_table) tc
order by some_column
limit 20;

Categories