I have a database with Orders, Order_content and Vendors table. I want to get the vendors in one order.
Vendor(vid, company_name, phone_number)
Order_content(ocid, product_name, vid)
Order(oid, ocid, address, name, phone_number)
I want to get the company_name, address and phone_number from the Vendor table that are related to a specific order.
What I have tried.
SELECT vendor.company_name, vendor.address, vendor.phone_number FROM vendor WHERE vendor.vid = order_content.vid AND order_content.oid = order.oid;
Using JOIN
SELECT vendor.company_name, vendor.address, vendor.phone_number AS vendor_details
FROM vendor
INNER JOIN orders_content ON (vendor.vid = orders_content.vendor_id AND orders_content.oid = orders.oid)
WHERE vendor.id;
The SQL is wrong and not working, some help will be appreciated. I think I am supposed to use a JOIN, I tried but the SQL throws an error.
Thanks.
You are only joining Vendor and Order_content, but not Order, so you are missing some fields as a result:
SELECT vendor.company_name, vendor.address, vendor.phone_number AS vendor_details
FROM vendor
INNER JOIN orders_content ON (vendor.vid = orders_content.vendor_id AND orders_content.oid = orders.oid)
INNER JOIN order ON (orders_content.ocid = orders.ocid);
Note that I removed the where clause, since it did not make any sense.
Related
I am stuck in 1 left join query in which I want to check multiple columns in on statement.
By default in the database, some column is null which I want to check in the on statement.
Now the issue is when I run a query using the OR operator it only runs the 1st condition and the rest are skipped.
If I use AND operator it throws an error.
So is there any way to get data from multiple conditions?
Here is my query:
$data = "SELECT
b.book_name, b.book_id,
b.cats_id, b.cats_id1,
b.cats_id2, b.cats_id3,
b.cats_id4, b.cats_id5,
b.cats_id6,
b.book_rating,
b.book_author,
b.book_stock,
b.book_publisher,
b.book_front_img,
b.book_status,
p.publisher_id,
p.publisher_name,
a.author_id,
a.author_name,
cat.cats_id,
cat.cats_name,
cat.cats_status
FROM
`books` AS b
LEFT JOIN `publisher` AS p
ON b.book_publisher = p.publisher_id
LEFT JOIN `author` AS a
ON b.book_author = a.author_id
LEFT JOIN categorys As cat
ON b.cats_id = cat.cats_id
OR b.cats_id1 = cat.cats_id
OR b.cats_id2 = cat.cats_id
OR b.cats_id3 = cat.cats_id
OR b.cats_id4 = cat.cats_id
OR b.cats_id5 = cat.cats_id
OR b.cats_id6 = cat.cats_id
GROUP BY
b.book_name
HAVING
cat.cats_name = '$search_data'
AND b.book_status = 1
ORDER BY
$sorting
LIMIT $offset, $page_limit"
You probably don't have more than one author displayed for your multi-author books either. You are misusing MySQL's notorious nonstandard extension to GROUP BY.
To troubleshoot this kind of query, disable that extension with SET sql_mode = CONCAT_WS(',',##sql_mode, 'ONLY_FULL_GROUP_BY'), then try your query again. You'll need more terms in your GROUP BY clause.
It looks like each books row has multiple category id columns. And it looks like you want to display information from your categorys table for each of them.
Use GROUP BY b.book_id, p.publisher_id, a.author_id, cats.cats_id to prevent MySQL's bizarro handling of GROUP BY from concealing your data.
I must add this: your multiple books.cats_id columns are not the SQLish way to handle your many-to-many relationship between books and categories. In the parlance of our trade, your books table is denormalized.
What you want is a new table called books_categorys with two columns, book_id and cats_id. It's called a join table. When a row is present in that table, it means a particular book is in a particular category. It's the SQLish way of handling a setup where each book can be in zero or more categorys. Here's an explanation. MySQL join many to many single row
Then you remove all the cats_id columns from books, and retrieve the categories like this.
Then you do something like this SELECT to get the categories.
SELECT books.id, books.name,
categorys.cats_id, categorys.cats_name, categorys.cats_status
FROM books
JOIN books_categorys ON books.book_id = books_categorys.book_id
JOIN categorys ON books_categorys.cats_id = categorys.cats_id
``
I have been through a few other posts relating to my error, but none of the solutions seem to work. I'm fairly new to SQL so sorry if its something really simple. I have two tables
Movie Inventory - which has columns movie_title, onhand_qty, and replacement_price
NotFlix - which has subscriber_name, queue_nbr, and movie_title
I am trying to join the two tables to output the total replacement price cost per customer, but when I do it gives me the error titled above. Here is my code, thanks in advance for any help!
SELECT subscriber_name, SUM (replacement_price) as replacement
FROM
(SELECT NotFlix.subscriber_name, NotFlix.movie_title, NotFlix.queue_nbr, MovieInventory.replacement_price
FROM NotFlix
INNER JOIN MovieInventory
ON NotFlix.movie_title = MovieInventory.movie_title
)
GROUP BY subscriber_name;
You are missing an alias:
SELECT AliasNameHere.subscriber_name, SUM (AliasNameHere.replacement_price) as replacement
FROM
(SELECT NotFlix.subscriber_name as subscriber_name, NotFlix.movie_title, NotFlix.queue_nbr, MovieInventory.replacement_price as replacement_price
FROM NotFlix
INNER JOIN MovieInventory
ON NotFlix.movie_title = MovieInventory.movie_title
) AliasNameHere
GROUP BY subscriber_name;
I Just don't get why are you doing a temporary table in FROM clause, you could just do a basic INNER JOIN here and potientialy avoid problem with alias name :
SELECT NotFlix.subscriber_name, SUM (MovieInventory.replacement_price) as replacement
FROM NotFlix
INNER JOIN MovieInventory
ON NotFlix.movie_title = MovieInventory.movie_title
GROUP BY subscriber_name;
I want to create a report with the top 20 customers (based on revenue).
I am using the query:
SELECT dbo.CustTable.AccountNum
,dbo.dirpartytable.NAME
,dbo.hcmworker.PERSONNELNUMBER
,dbo.CustInvoiceJour.SALESBALANCE
,dbo.custinvoicejour.QTY
FROM dbo.CustTable
inner JOIN dbo.HCMWORKER ON dbo.HCMWORKER.RECID = dbo.CustTable.KEV_Worker
inner join dbo.custInvoiceJour on CustInvoiceJour.OrderAccount = CustTable.AccountNum
inner join dbo.dirpartytable on dirpartytable.recid = custtable.PARTY
where CustTable.KEV_Worker = '5633561745'
ORDER BY SalesBalanceMst DESC
I can't find the relation for the customer revenue, after all, that is how I want to sort the report. I am sorting on SalesBalanceMST right now while building the report. Also I am getting multiple records when executing this query.
What am i doing wrong?
EDIT: I now realize I am showing each Invoice Journal, how can I display the Total Revenue of the customer?
A similar search from AX 2012:
CustInvoiceJour CustInvoiceJour;
CustTable CustTable;
DirPartyTable DirPartyTable;
select forceLiterals generateonly sum(SalesBalanceMST), sum(Qty) from CustInvoiceJour
where CustInvoiceJour.OrderAccount == '102372200'
&& CustInvoiceJour.InvoiceDate > today()-365
join TableId from CustTable
group AccountNum
where CustTable.AccountNum == CustInvoiceJour.OrderAccount
join TableId from DirPartyTable
group Name
where DirPartyTable.RecId == CustTable.Party;
info(CustInvoiceJour.getSQLStatement());
This shows the following SQL:
SELECT SUM(T1.SALESBALANCEMST),SUM(T1.QTY),T2.ACCOUNTNUM,T3.NAME
FROM CUSTINVOICEJOUR T1
CROSS JOIN CUSTTABLE T2
CROSS JOIN DIRPARTYTABLE T3
WHERE (((T1.PARTITION=5637144576) AND (T1.DATAAREAID=N'xxx'))
AND ((T1.ORDERACCOUNT=N'102372200')
AND (T1.INVOICEDATE>{ts '2015-11-06 00:00:00.000'})))
AND (((T2.PARTITION=5637144576) AND (T2.DATAAREAID=N'xxx'))
AND (T2.ACCOUNTNUM=T1.ORDERACCOUNT))
AND ((T3.PARTITION=5637144576)
AND (T3.RECID=T2.PARTY))
GROUP BY T2.ACCOUNTNUM,T3.NAME
ORDER BY T2.ACCOUNTNUM,T3.NAME
What is different from your query:
no join on HcmWorker, as I do not have your custom field.
Using sum() to aggregate
selecting on InvoiceDate
selection on OrderAccount
selection on DataAreaId, really important for performance, implicit in AX
selection on Partition, really important for performance, implicit in AX
You cannot directly sort on a sum, but may on a nested SQL query.
I do not know exactly what is wrong in your query but perhaps this information can help you.
Check this standard report CustTopCustomersbyYTDSales, It has some good queries to do that.
https://technet.microsoft.com/en-us/library/hh389751.aspx
I have a query which I am working on, basically I have 3 columns:
Code: The users Code
Orders Taken: The orders which have been taken
Orders Taken From an External Call
Basically I just need a way to only allow Orders From External Calls to have a where clauses, when I add in my WHERE clause, it does it for both tables.
My query so far:
SELECT T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
Count(T_Temp_RestrictedProductSalesHistory.CustomerCode) AS [Orders Taken],
Count(T_Temp_RestrictedProductSalesHistory.CustomerCode) AS [Orders From External Calls]
FROM T_Temp_RestrictedDiaryCalls
INNER JOIN T_Temp_RestrictedProductSalesHistory
ON (T_Temp_RestrictedDiaryCalls.CustomerCode = T_Temp_RestrictedProductSalesHistory.CustomerCode)
AND (T_Temp_RestrictedDiaryCalls.CallDate = T_Temp_RestrictedProductSalesHistory.EntryDate)
GROUP BY T_Temp_RestrictedDiaryCalls.AccreditedDomainCode;
Any help will be greatly appreciated.
If I've got it right you should use CASE statement in the [Orders From External Calls] definition:
SELECT T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
Count(T_Temp_RestrictedProductSalesHistory.CustomerCode) AS [Orders Taken],
sum( CASE WHEN <Your condition here>
THEN 1
ELSE 0
END) AS [Orders From External Calls]
FROM T_Temp_RestrictedDiaryCalls
INNER JOIN T_Temp_RestrictedProductSalesHistory
ON (T_Temp_RestrictedDiaryCalls.CustomerCode = T_Temp_RestrictedProductSalesHistory.CustomerCode)
AND (T_Temp_RestrictedDiaryCalls.CallDate = T_Temp_RestrictedProductSalesHistory.EntryDate)
GROUP BY T_Temp_RestrictedDiaryCalls.AccreditedDomainCode;
Based on what you said on comments one column might have the count of all rows, and other column just show value on specify case.
So:
select table1.a,count(table1.b),
(select count(table2.c) from table2 where "where clause")
from table1
If I understand you correctly, you want both of those Orders columns to count data from the same table, but with different restrictions on which records from the table are counted and which are not. So do something like:
SELECT T_Temp_RestrictedDiaryCalls.AccreditedDomainCode,
Count(SalesHistoryForAllOrders.CustomerCode) AS [Orders Taken],
Count(SalesHistoryForExternalOrders.CustomerCode) AS [Orders From External Calls]
FROM T_Temp_RestrictedDiaryCalls
INNER JOIN T_Temp_RestrictedProductSalesHistory SalesHistoryForAllOrders
ON (T_Temp_RestrictedDiaryCalls.CustomerCode = SalesHistoryForAllOrders.CustomerCode)
AND (T_Temp_RestrictedDiaryCalls.CallDate = SalesHistoryForAllOrders.EntryDate)
INNER JOIN T_Temp_RestrictedProductSalesHistory SalesHistoryForExternalOrders
ON (T_Temp_RestrictedDiaryCalls.CustomerCode = SalesHistoryForExternalOrders.CustomerCode)
AND (T_Temp_RestrictedDiaryCalls.CallDate = SalesHistoryForExternalOrders.EntryDate)
GROUP BY T_Temp_RestrictedDiaryCalls.AccreditedDomainCode;
Explanation:
By INNER JOINing the table two times and aliasing it each time, we now have two separate representations of the table to work with (called SalesHistoryForAllOrders and SalesHistoryForExternalOrders).
You are then free to place a WHERE clause that refers to either one of them separately, and it will ONLY affect that column, not the other one. So either do:
WHERE SalesHistoryForExternalOrders.IsAnExternalOrder > 0
or just add an additional AND to the second INNER JOIN:
AND SalesHistoryForExternalOrders.IsAnExternalOrder > 0
, the result is the same: that clause will only be applied the External Calls column.
MySQL Server Version: Server version: 4.1.14
MySQL client version: 3.23.49
Tables under discussion: ads_list and ads_cate.
Table Relationship: ads_cate has many ads_list.
Keyed by: ads_cate.id = ads_list.Category.
I am not sure what is going on here, but I am trying to use COUNT() in a simple agreggate query, and I get blank output.
Here is a simple example, this returns expected results:
$queryCats = "SELECT id, cateName FROM ads_cate ORDER BY cateName";
But if I modify it to add the COUNT() and the other query data I get no array return w/ print_r() (no results)?
$queryCats = "SELECT ads_cate.cateName, ads_list.COUNT(ads_cate.id),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName ORDER BY cateName";
Ultimately, I am trying to get a count of ad_list items in each category.
Is there a MySQL version conflict on what I am trying to do here?
NOTE: I spent some time breaking this down, item by item and the COUNT() seems to cause the array() to disappear. And the the JOIN seemed to do the same thing... It does not help I am developing this on a Yahoo server with no access to the php or mysql error settings.
I think your COUNT syntax is wrong. It should be:
COUNT(ads_cate.id)
or
COUNT(ads_list.id)
depending on what you are counting.
Count is an aggregate. means ever return result set at least one
here you be try count ads_list.id not null but that wrong. how say Myke Count(ads_cate.id) or Count(ads_list.id) is better approach
you have inner join ads_cate.id = ads_list.category so Count(ads_cate.id) or COUNT(ads_list.id) is not necessary just count(*)
now if you dont want null add having
only match
SELECT ads_cate.cateName, COUNT(*),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
having not count(*) is null
ORDER BY cateName
all
SELECT ads_cate.cateName, IFNULL(COUNT(*),0),
FROM ads_cate LEFT JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
ORDER BY cateName
Did you try:
$queryCats = "SELECT ads_cate.cateName, COUNT(ads_cate.id)
FROM ads_cate
JOIN ads_list ON ads_cate.id = ads_list.category
GROUP BY ads_cate.cateName";
I am guessing that you need the category to be in the list, in that case the query here should work. Try it without the ORDER BY first.
You were probably getting errors. Check your server logs.
Also, see what happens when you try this:
SELECT COUNT(*), category
FROM ads_list
GROUP BY category
Your array is empty or disappear because your query has errors:
there should be no comma before the FROM
the "ads_list." prefix before COUNT is incorrect
Please try running that query directly in MySQL and you'll see the errors. Or try echoing the output using mysql_error().
Now, some other points related to your query:
there is no need to do ORDER BY because GROUP BY by default sorts on the grouped column
you are doing a count on the wrong column that will always give you 1
Perhaps you are trying to retrieve the count of ads_list per ads_cate? This might be your query then:
SELECT `ads_cate`.`cateName`, COUNT(`ads_list`.`category`) `cnt_ads_list`
FROM `ads_cate`
INNER JOIN `ads_list` ON `ads_cate`.`id` = `ads_list`.`category`
GROUP BY `cateName`;
Hope it helps?