I have 2 tables, names and phones I did this for the query
$result = mysqli_query($mysqli, "SELECT * FROM names ORDER BY fname ASC
RIGHT JOIN phones ON phones.id=names.phone_id"
);
I got $result as false. My names table has a column named phone_id and it's a PK of phones's id, like so
names
- phone_id (FK)
phones
- id (PK)
What's wrong with my sql above?
The syntax should go like this:
SELECT *
FROM names
RIGHT JOIN phones ON phones.id = names.phone_id
ORDER BY fname ASC
The ORDER BY had to be moved to the end.
Order by should be the last part of your query
SELECT *
FROM names n
RIGHT JOIN phones p ON p.id=n.phone_id
ORDER BY fname ASC
Start using alias names to make the query more readable
You should use ORDER BY as last clause of your query. Becasue order by i.e. sorting works at last after fetch.
SELECT *
FROM names as n
RIGHT JOIN phones as p ON p.id=n.phone_id
ORDER BY fname ASC
To see more abour ORDER BY you can check the manual link
Related
I have a MySQL table from which I want to extract attendance information(Student Id, course/subject for attendance, date range,whether the student was present or not). I have written the following query:
SELECT
COUNT(a_id),
(
SELECT COUNT(*) FROM attendance
WHERE state = 'present'
AND `dater` BETWEEN '$a' AND '$b'
) AS Count,
stud_id
FROM attendance
WHERE
stud_id =(SELECT id FROM users WHERE NAME = '$stud')
Which is giving me the correct results, but when I change the student,its not giving me the correct count for the days recorded for present. Not mention that I have not yet added the course parameter into the query
The MySQL table is as follows:
I need help for the query to return the desired results(Count the accurate days present for each student, as well as adding the course parameter into the query so that the query will look for attendance records for a specific course, for a specific student, for a specified date range).
Looks like you want to seperate your queries:
Select (select count(*) from <database>.attendance where state = 'present' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as present, (select count(*) from <database>.attendance where state = 'absent' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as absent from <database>.attendance WHERE stud_id =(SELECT id FROM users WHERE NAME = '$stud');
try this :)
Resolved it using JOIN as follows:
SELECT u.id, a.stud_id, a.course_id, count(*) FROM attendance a
JOIN users u ON u.id=a.stud_id
JOIN courses c ON c.c_id=a.course_id
WHERE a.state='present' and dater between '2017-09-01' and '2017-09-14'
GROUP BY a.stud_id, a.course_id;
Thanks for your help.
I am new to PHP and SQL; I am writing a SQL query to display records with the following logic:
There are 9 cells in sql table. I want to search records using combinations of 3 parameters. That are search between 2 dates, search in location and search in property category type.
Search criteria looks like this:
Date From : _________(date picker) - Date Till:______________(date picker)
Sales Agent : Dropdown ( dehi, mumbai,.....,)
Mobile : __________ (text)
Results Combination Required:
a. All 3 combination True - (User Fills the date, sales agent, mobile.)
b. Either of the combination is True. (User only fills either of one parameter.)
c. Only 2 Combination are True. (User fills 2 parameter combination ie, date and mobile(or) mobile & sales agent (or) sales agent & date)
Problem: I'm not able to do only one combination.
Here is my SQL query and page syntax:
if(isset($_POST["submit"]))
{
$date11=$_POST["date1"];
$date22=$_POST["date2"];
$salesagent1=$_POST["salesagent"];
$mobile1=$_POST["mobile"];
$result = "select
ordertable.order_date,
ordertable.order_id,
customer.cust_name,
customer.cust_mobile,
customer.cust_email,
customer.cust_city,
ordertable.quantity,
ordertable.total,
orderstatus.order_sta,
salesagent.name
from customer inner join ordertable
on customer.custid=ordertable.cust_id inner join salesagent
on salesagent.said=ordertable.sales_id inner join orderstatus
on orderstatus.id= (select order_statusid from orderhistory where order_id1= ordertable.order_id order by date_added desc limit 1)
where (ordertable.order_date between '$date11' and '$date22') or (customer.cust_mobile='$mobile1') or (ordertable.sales_id='$salesagent1')
order by ordertable.order_id desc";
$records=mysqli_query($CON,$result);
Set null or whatever you choose to do, to each parameters when it is empty:
$result = "select
ordertable.order_date,
ordertable.order_id,
customer.cust_name,
customer.cust_mobile,
customer.cust_email,
customer.cust_city,
ordertable.quantity,
ordertable.total,
orderstatus.order_sta,
salesagent.name
from customer inner join ordertable
on customer.custid=ordertable.cust_id inner join salesagent
on salesagent.said=ordertable.sales_id inner join orderstatus
on orderstatus.id= (select order_statusid from orderhistory where order_id1= ordertable.order_id order by date_added desc limit 1)
where ('$date11' IS NULL OR '$date22' IS NULL OR ordertable.order_date between '$date11' and '$date22') AND ('$mobile1' IS NULL OR customer.cust_mobile='$mobile1') AND ('$salesagent1' IS NULL OR ordertable.sales_id='$salesagent1')
order by ordertable.order_id desc";
I found the following mysqli query on the internet. It displays top 3 sold cars
//create conection with mysql database.
$conn = mysqli_connect("localhost","root","","cars");
//query
$select = "SELECT ord.*, sum(amount) as amt from orders as ord GROUP BY id_car order by amt desc limit 0,3";
$data = mysqli_query($conn,$select);
This query works fine but I would like if anyone can explain me this first section of the query: SELECT ord.*,
It seems like "ord" refers to orders but is it the same as saying: SELECT * FROM orders??
See table in the screenshot image
orders table
In the query there is orders as ord this gives the orders table an 'alias' of the orders table, so ord.* means orders.*
It is a bit redundant in this query to be honest, mainly used if there are multiople tables in a query :)
For this query you can simply do:
$select = "SELECT *, sum(amount) as amt from orders GROUP BY id_car order by amt desc limit 0,3";
Let's break it down:
a) Select all fields from table named ord which will be defined in c)
SELECT ord.*,
b) Select sum of column amount and name it amt
sum(amount) as amt
c) Use table orders for the query and define an alias name ord for that table, see a)
from orders as ord
It is same as select * from tableName,it will fetch all columns from table.But alias Name is given for the table. Using alias Name is best practices for joining the multiple tables.
since you are using single table you can do this also.
SELECT *, sum(amount) as amt from orders as ord GROUP BY id_car order by amt desc limit 0,3
i have two tables in my db .. one is Messages and the other is Contacts... both tables contain the mobile_number field.. in Contacts table there is no duplicate numbers ... but in Messages tables there are several duplicate numbers in mobileNo field...what i am doing is write now i am selecting the distinct mobile numbers from the Messages tables and then i am comparring the distinct numbers from the contacts table ... so if the messages_mobileNo is found on the contacts table then give me the contact name against the number otherwise messages_mobileNo ... so the problem is distinct not working .. i am not able to get the distinct numbers from the Messages table ... it is showing me the duplicate numbers
here is my query
SELECT DISTINCT Message.mobileNo,
Contact.mobileNo,
Contact.workNo,
Contact.homeNo,
Contact.other,
Contact.name,
Message.body,
Message.idTextMessage
FROM cakephp_db.textmessage AS Message
LEFT JOIN cakephp_db.contacts AS Contact ON (Message.user_id = Contact.user_id
AND ((Message.mobileNo = Contact.mobileNo)
OR (Message.mobileNo = Contact.workNo)
OR (Message.mobileNo = Contact.homeNo)
OR (Message.mobileNo = Contact.other)))
WHERE Message.User_id = 23
ORDER BY Message.idTextMessage DESC LIMIT 6
So your trying to get the last 6 messages of a person if I'm right?
SELECT Message.mobileNo,
Contact.mobileNo,
Contact.workNo,
Contact.homeNo,
Contact.other,
Contact.name,
Message.body,
Message.idTextMessage
FROM cakephp_db.textmessage AS Message
LEFT JOIN cakephp_db.contacts AS Contact ON Message.user_id = Contact.user_id
AND Message.mobileNo IN (Contact.mobileNo, Contact.workNo, Contact.homeNo, Contact.other)
WHERE Message.User_id = 23
GROUP BY Message.mobileNo
ORDER BY Message.idTextMessage DESC LIMIT 6
add a GROUP BY Message.mobileNo before your ORDER BY
If you are using MySQL SELECT DISTINCT with an ORDER BY added to it, you will have to create a temporary table where it can store its results. Here is a link offering more help:
MySQL DISTINCT Optimization
I have 4 tables:
categories - id, position
subcategories - id, categories_id, position
sub_subcategories - id, subcategories_id, position
product - id, sub_subcategories_id, prod_pos
Now I'm doing tests to find out what's wrong with my query.
So i want to select sub_subcategories, and to get someting like that:
[[1,2,3,4,5,6], [1,2,3,4,5,6,7]], [[1,2,3,4,5,6], [1,2,3,4]]
Each [] means: big - categories, small - subcategory, and the numbers are position in sub_subcategories. I want the [] to order by their "position" field, so query:
SELECT id FROM sub_subcategories_id
WHERE subcategories_id IN (
SELECT id
FROM subcategories_id
WHERE categories_id IN (
SELECT id FROM categories
WHERE id = 'X' ORDER BY position)
ORDER BY position)
ORDER BY position
is somehow wrong, because I get:
1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,6,6,6,7
Dunno why - does last "ORDER BY position" destroy everything?
You need to apply all of your desired ordering in the outermost query - ORDERing within subqueries doesn't make any sense - the question "is this ID in <this list>?" has the same answer, no matter what order the list is in (indeed, more property, <this list> is a set, which has no order).
So you'll need to get all of the columns you need to order by in your outermost query.
Something like:
SELECT ssi.ID
from
sub_subcategories_id ssi
inner join
subcategories_id si
on
ssi.subcategories_id = si.id
inner join
categories c
on
si.categories_id = c.id
where
c.id = 'X'
order by
c.position,
si.position,
ssi.position
As it stands now, your query would never return a 'set' of numbers as is. If you ignore all the subselects, you're essentially doing:
SELECT id FROM sub_subcategories_id
ORDER BY position
which would only return one column: the sub_sub_categories_id. You'd be better off doing something like:
SELECT cat.id, subcat.id, subsubcat.id
FROM sub_sub_categories AS subsubcat
LEFT JOIN sub_categories AS subcat ON subcat.id = subsubcat.subcategories.id
LEFT JOIN categories AS cat ON cat.id = subcat.category_id
WHERE (cat.id = 'X')
ORDER BY cat.id, subcat.id, subsubcat.id
That'll return 3 columns ordered by the various IDs. If you don't need the individual sub_sub_categories values, and just want them as a single string value, you can mess around with GROUP_CONCAT() and do various bits of grouping:
SELECT cat.id, subcat.id, GROUP_CONCAT(subsubcat.id)
FROM ...
...
WHERE (cat.id = 'X')
GROUP BY cat.id, subcat.id, subsubcat.id
ORDER BY ...